Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(30724): clear "x-middleware-next" header when chaining middlewares #30866

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/next/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,9 @@ export default class Server {
})

for (let [key, value] of result.response.headers) {
allHeaders.append(key, value)
if (key !== 'x-middleware-next') {
allHeaders.append(key, value)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this change made?

It means that a middleware cannot longer set headers without breaking the middleware chain as we have below:

        if (!result.response.headers.has('x-middleware-next')) {
          break
        }

This will break some of the examples, like this one.

It also means that a middleware cannot simply add a cookie and keep the rest as is. For example, you may want to add a csrf cookie if missing, but not break the middleware chain or return a custom Response.

}

if (!this.renderOpts.dev) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { NextResponse } from 'next/server'

export async function middleware(request, _event) {
if (request.nextUrl.searchParams.get('deep-intercept') === 'true') {
return new NextResponse('intercepted!')
}
const next = NextResponse.next()
next.headers.set('x-deep-header', 'valid')
next.headers.append('x-append-me', 'deep')
Expand Down
8 changes: 8 additions & 0 deletions test/integration/middleware/core/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,14 @@ function responseTests(locale = '') {
'foo=oatmeal',
])
})

it(`${locale} should be intercepted by deep middleware`, async () => {
const res = await fetchViaHTTP(
context.appPort,
`${locale}/responses/deep?deep-intercept=true`
)
expect(await res.text()).toBe('intercepted!')
})
}

function interfaceTests(locale = '') {
Expand Down