Commit 52a078da authored by JJ Kasper's avatar JJ Kasper Committed by Jiachi Liu

Update middleware request header (#77201)

This just adds an additional header to our internal filtering list for
middleware.
parent 4698ad64
......@@ -166,10 +166,13 @@ export async function initialize(opts: {
renderServer.instance =
require('./render-server') as typeof import('./render-server')
const allowedOrigins = [
'localhost',
...(config.experimental.allowedDevOrigins || []),
]
const randomBytes = new Uint8Array(8)
crypto.getRandomValues(randomBytes)
const middlewareSubrequestId = Buffer.from(randomBytes).toString('hex')
;(globalThis as any)[Symbol.for('@next/middleware-subrequest-id')] =
middlewareSubrequestId
const allowedOrigins = ['localhost', ...(config.allowedDevOrigins || [])]
if (opts.hostname) {
allowedOrigins.push(opts.hostname)
}
......
......@@ -57,5 +57,16 @@ export const filterInternalHeaders = (
if (INTERNAL_HEADERS.includes(header)) {
delete headers[header]
}
// If this request didn't origin from this session we filter
// out the "x-middleware-subrequest" header so we don't skip
// middleware incorrectly
if (
header === 'x-middleware-subrequest' &&
headers['x-middleware-subrequest-id'] !==
(globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]
) {
delete headers['x-middleware-subrequest']
}
}
}
......@@ -373,6 +373,10 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),
store.headers.get('x-middleware-subrequest') ?? ''
)
}
init.headers.set(
'x-middleware-subrequest-id',
(globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]
)
const prevs =
init.headers.get(`x-middleware-subrequest`)?.split(':') || []
......
......@@ -144,6 +144,19 @@ describe('Middleware Runtime', () => {
}
}
it('should filter request header properly', async () => {
const res = await next.fetch('/redirect-to-somewhere', {
headers: {
'x-middleware-subrequest':
'middleware:middleware:middleware:middleware:middleware',
},
redirect: 'manual',
})
expect(res.status).toBe(307)
expect(res.headers.get('location')).toContain('/somewhere')
})
it('should handle 404 on fallback: false route correctly', async () => {
const res = await next.fetch('/ssg-fallback-false/first')
expect(res.status).toBe(200)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment