Unverified Commit 8a511d6a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Match subrequest handling for edge and node (#77476)

Backports https://github.com/vercel/next.js/pull/77474 to v14
parent d36a1f3c
...@@ -149,12 +149,6 @@ export async function initialize(opts: { ...@@ -149,12 +149,6 @@ export async function initialize(opts: {
renderServer.instance = renderServer.instance =
require('./render-server') as typeof import('./render-server') require('./render-server') as typeof import('./render-server')
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 requestHandlerImpl: WorkerRequestHandler = async (req, res) => { const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {
// internal headers should not be honored by the request handler // internal headers should not be honored by the request handler
if (!process.env.NEXT_PRIVATE_TEST_HEADERS) { if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {
......
...@@ -57,16 +57,5 @@ export const filterInternalHeaders = ( ...@@ -57,16 +57,5 @@ export const filterInternalHeaders = (
if (INTERNAL_HEADERS.includes(header)) { if (INTERNAL_HEADERS.includes(header)) {
delete headers[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']
}
} }
} }
...@@ -354,27 +354,6 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), ...@@ -354,27 +354,6 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),
init.headers = new Headers(init.headers ?? {}) init.headers = new Headers(init.headers ?? {})
// Forward subrequest header from incoming request to outgoing request
const store = requestStore.getStore()
if (
store?.headers.has('x-middleware-subrequest') &&
!init.headers.has('x-middleware-subrequest')
) {
init.headers.set(
'x-middleware-subrequest',
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(':') || []
const value = prevs.concat(options.moduleName).join(':')
init.headers.set('x-middleware-subrequest', value)
if (!init.headers.has('user-agent')) { if (!init.headers.has('user-agent')) {
init.headers.set(`user-agent`, `Next.js Middleware`) init.headers.set(`user-agent`, `Next.js Middleware`)
} }
......
...@@ -83,25 +83,6 @@ export async function getRuntimeContext(params: { ...@@ -83,25 +83,6 @@ export async function getRuntimeContext(params: {
export const run = withTaggedErrors(async function runWithTaggedErrors(params) { export const run = withTaggedErrors(async function runWithTaggedErrors(params) {
const runtime = await getRuntimeContext(params) const runtime = await getRuntimeContext(params)
const subreq = params.request.headers[`x-middleware-subrequest`]
const subrequests = typeof subreq === 'string' ? subreq.split(':') : []
const MAX_RECURSION_DEPTH = 5
const depth = subrequests.reduce(
(acc, curr) => (curr === params.name ? acc + 1 : acc),
0
)
if (depth >= MAX_RECURSION_DEPTH) {
return {
waitUntil: Promise.resolve(),
response: new runtime.context.Response(null, {
headers: {
'x-middleware-next': '1',
},
}),
}
}
const edgeFunction: (args: { const edgeFunction: (args: {
request: RequestData request: RequestData
......
import { createNextDescribe } from 'e2e-utils'
const bathPath = process.env.BASE_PATH ?? ''
createNextDescribe(
'app-routes-subrequests',
{
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('shortcuts after 5 subrequests', async () => {
expect(JSON.parse(await next.render(bathPath + '/'))).toEqual({
count: 5,
})
})
}
)
import { NextRequest, NextResponse } from 'next/server'
export const runtime = 'edge'
let count = 0
export const GET = async (req: NextRequest) => {
await fetch(req.nextUrl)
count++
return NextResponse.json({ count })
}
/**
* @type {import('next').NextConfig}
*/
const config = {
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = config
...@@ -102,19 +102,6 @@ describe('Middleware Runtime', () => { ...@@ -102,19 +102,6 @@ describe('Middleware Runtime', () => {
} }
function runTests({ i18n }: { i18n?: boolean }) { function runTests({ i18n }: { i18n?: boolean }) {
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 () => { it('should handle 404 on fallback: false route correctly', async () => {
const res = await next.fetch('/ssg-fallback-false/first') const res = await next.fetch('/ssg-fallback-false/first')
expect(res.status).toBe(200) 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