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:
Balázs Orbán 2023-10-13 19:58:33 +02:00 committed by GitHub
parent ac8a6035df
commit fe0bfbf911
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 0 deletions

View file

@ -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)

View file

@ -0,0 +1,3 @@
export function GET(req: Request) {
return Response.json(Object.fromEntries(req.headers))
}

View file

@ -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)
})
})