Middleware redirect behavior breaks when duplicate headers are present.
The issue occurs when duplicate `x-forwarded-proto` headers are present in a request, causing middleware redirects to use incorrect URLs. The bug appears to have been introduced in v13.4.13, potentially related to request cloning or header parsing logic. The problem is reproducible and test-focused, but the exact fix requires understanding of Next.js middleware and header handling.
Not the actual environment but can be reproduced here:
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:20 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T6000
Binaries:
Node: 18.16.0
npm: 9.5.1
Yarn: 1.22.19
pnpm: 8.6.12
Relevant Packages:
next: 13.4.19
eslint-config-next: 13.4.19
react: 18.2.0
react-dom: 18.2.0
typescript: 5.1.6
Next.js Config:
output: N/A
Middleware / Edge (API routes, runtime)
https://github.com/coneno/nextjs-middleware-redirect-issue
Start dev or test server.
Using:
curl --location 'http://localhost:3000/' --header 'x-forwarded-proto: https' --header 'x-forwarded-proto: https' -i
Results in:
HTTP/1.1 307 Temporary Redirect
date: Wed, 23 Aug 2023 14:56:19 GMT
location: https://localhost:3000/test
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
Note Location is an absolute path compared to expected redirect (see below).
Having a simple redirect middleware:
import { NextResponse, NextRequest } from 'next/server'
export const config = {
matcher: ['/']
}
export function middleware(req: NextRequest) {
const newURL = req.nextUrl.clone();
newURL.pathname = `/test`;
return NextResponse.redirect(newURL);
}
x-forwarded-proto: https present in the request header (simulated in curl command to reproduce)x-forwarded-proto: https in the header, it brClaim this issue to let others know you're working on it. You'll earn 20 points when you complete it!