Skip to content

Commit

Permalink
fix: add x-forwarded-* headers (vercel#56797)
Browse files Browse the repository at this point in the history
### What?

Adding back `x-forwarded-*` headers.


### Why?

Starting with vercel#52492, these headers were lost.

### How?

We can populate these headers before executing a request.

Closes NEXT-1663
Fixes vercel#55942
  • Loading branch information
balazsorban44 committed Oct 13, 2023
1 parent ac8a603 commit fe0bfbf
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/next/src/server/lib/router-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions test/e2e/app-dir/x-forwarded-headers/app/route.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function GET(req: Request) {
return Response.json(Object.fromEntries(req.headers))
}
13 changes: 13 additions & 0 deletions test/e2e/app-dir/x-forwarded-headers/x-forwarded-headers.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})

0 comments on commit fe0bfbf

Please sign in to comment.