# Error: Middleware set header 'X' after response headers were already sent.

- **ID:** `nextjs/middleware-response-header-override`
- **Domain:** nextjs
- **Category:** protocol_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## 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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Next.js 13.5 | active | — | — |
| Next.js 14.0 | active | — | — |
| Next.js 14.2 | active | — | — |
| Next.js 15.0 | active | — | — |

## Workarounds

1. **Set headers before calling NextResponse.next() or before sending the response. Use NextResponse.rewrite() or NextResponse.redirect() with headers in the constructor.** (90% success)
   ```
   Set headers before calling NextResponse.next() or before sending the response. Use NextResponse.rewrite() or NextResponse.redirect() with headers in the constructor.
   ```
2. **Use the 'request' object to read headers and set them on a new response. Avoid modifying the original response after it's used.** (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.
   ```
3. **If you need to set headers conditionally, create a new NextResponse object instead of mutating the one from NextResponse.next().** (80% success)
   ```
   If you need to set headers conditionally, create a new NextResponse object instead of mutating the one from NextResponse.next().
   ```

## Dead Ends

- **** — response.headers.set() is synchronous; adding await does not change the timing. The header is still set after the response is sent. (90% 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. (85% fail)
- **** — Both set() and append() modify the same header object; the error is about timing, not the method used. The response is already sent. (80% fail)
