Error: Middleware set header 'X' after response headers were already sent.
ID: nextjs/middleware-response-header-override
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Next.js 13.5 | active | — | — | — |
| Next.js 14.0 | active | — | — | — |
| Next.js 14.2 | active | — | — | — |
| Next.js 15.0 | active | — | — | — |
Root Cause
The middleware function attempts to modify response headers (e.g., via response.headers.set()) after the response has already been sent or after calling NextResponse.next() without properly cloning the response.
generic中文
中间件函数在响应已发送或调用 NextResponse.next() 后尝试修改响应头(例如,通过 response.headers.set()),而没有正确克隆响应。
Official Documentation
https://nextjs.org/docs/app/building-your-application/routing/middlewareWorkarounds
-
90% success Set headers before calling NextResponse.next() or before sending the response. Use NextResponse.rewrite() or NextResponse.redirect() with headers in the constructor.
Set headers before calling NextResponse.next() or before sending the response. Use NextResponse.rewrite() or NextResponse.redirect() with headers in the constructor.
-
85% success Use the 'request' object to read headers and set them on a new response. Avoid modifying the original response after it's used.
Use the 'request' object to read headers and set them on a new response. Avoid modifying the original response after it's used.
-
80% success If you need to set headers conditionally, create a new NextResponse object instead of mutating the one from NextResponse.next().
If you need to set headers conditionally, create a new NextResponse object instead of mutating the one from NextResponse.next().
中文步骤
在调用 NextResponse.next() 或发送响应之前设置标头。使用带有标头的 NextResponse.rewrite() 或 NextResponse.redirect() 在构造函数中设置。
使用 'request' 对象读取标头并在新响应上设置。避免在原始响应被使用后修改它。
如果需要有条件地设置标头,创建一个新的 NextResponse 对象,而不是修改 NextResponse.next() 返回的对象。
Dead Ends
Common approaches that don't work:
-
90% fail
response.headers.set() is synchronous; adding await does not change the timing. The header is still set after the response is sent.
-
85% fail
The response is already sent by the time the timeout executes, and headers cannot be modified after the fact. This also introduces race conditions.
-
80% fail
Both set() and append() modify the same header object; the error is about timing, not the method used. The response is already sent.