fix: add x-forwarded-*
headers (#56797)
### What? Adding back `x-forwarded-*` headers. ### Why? Starting with #52492, these headers were lost. ### How? We can populate these headers before executing a request. Closes NEXT-1663 Fixes #55942
This commit is contained in:
parent
ac8a6035df
commit
fe0bfbf911
3 changed files with 28 additions and 0 deletions
|
@ -33,6 +33,7 @@ import {
|
|||
PERMANENT_REDIRECT_STATUS,
|
||||
} from '../../shared/lib/constants'
|
||||
import { DevBundlerService } from './dev-bundler-service'
|
||||
import type { TLSSocket } from 'tls'
|
||||
|
||||
const debug = setupDebug('next:router-server:main')
|
||||
|
||||
|
@ -222,6 +223,17 @@ export async function initialize(opts: {
|
|||
'x-middleware-invoke': '',
|
||||
'x-invoke-path': invokePath,
|
||||
'x-invoke-query': encodeURIComponent(JSON.stringify(parsedUrl.query)),
|
||||
'x-forwarded-host':
|
||||
req.headers['x-forwarded-host'] ?? req.headers.host ?? opts.hostname,
|
||||
'x-forwarded-port':
|
||||
req.headers['x-forwarded-port'] ?? opts.port.toString(),
|
||||
'x-forwarded-proto':
|
||||
req.headers['x-forwarded-proto'] ??
|
||||
(req.socket as TLSSocket).encrypted
|
||||
? 'https'
|
||||
: 'http',
|
||||
'x-forwarded-for':
|
||||
req.headers['x-forwarded-for'] ?? req.socket.remoteAddress,
|
||||
...(additionalInvokeHeaders || {}),
|
||||
}
|
||||
Object.assign(req.headers, invokeHeaders)
|
||||
|
|
3
test/e2e/app-dir/x-forwarded-headers/app/route.tsx
Normal file
3
test/e2e/app-dir/x-forwarded-headers/app/route.tsx
Normal file
|
@ -0,0 +1,3 @@
|
|||
export function GET(req: Request) {
|
||||
return Response.json(Object.fromEntries(req.headers))
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
import { createNextDescribe } from 'e2e-utils'
|
||||
|
||||
createNextDescribe('x-forwarded-headers', { files: __dirname }, ({ next }) => {
|
||||
it('should include x-forwarded-* headers', async () => {
|
||||
const res = await next.fetch('/')
|
||||
const headers = await res.json()
|
||||
const url = new URL(next.url)
|
||||
expect(headers['x-forwarded-host']).toBe(url.host)
|
||||
expect(headers['x-forwarded-port']).toBe(url.port)
|
||||
expect(headers['x-forwarded-proto']).toBe(url.protocol.replace(':', ''))
|
||||
console.log(headers)
|
||||
})
|
||||
})
|
Loading…
Reference in a new issue