Skip to content

Commit da7aa22

Browse files
authored
fix: correctly handle middleware header mutations (#225)
* fix: correctly handle middleware header mutations * Add comment and remove log
1 parent 3befee4 commit da7aa22

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

edge-runtime/lib/headers.ts

+18-4
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,34 @@ export const InternalHeaders = {
1212
// * https://github.com/vercel/next.js/blob/43c9d8940dc42337dd2f7d66aa90e6abf952278e/packages/next/server/web/spec-extension/response.ts#L10-L27
1313
export function updateModifiedHeaders(requestHeaders: Headers, responseHeaders: Headers) {
1414
const overriddenHeaders = responseHeaders.get('x-middleware-override-headers')
15-
1615
if (!overriddenHeaders) {
1716
return
1817
}
1918

20-
const headersToUpdate = overriddenHeaders.split(',').map((header) => header.trim())
19+
const headersToUpdate = new Set(overriddenHeaders.split(',').map((header) => header.trim()))
20+
21+
// We can't iterate this directly, because we modify the headers in the loop.
22+
// This was causing values to be skipped. By spreading them first we avoid that.
23+
for (const key of [...requestHeaders.keys()]) {
24+
if (!headersToUpdate.has(key)) {
25+
requestHeaders.delete(key)
26+
}
27+
}
2128

2229
for (const header of headersToUpdate) {
2330
const oldHeaderKey = 'x-middleware-request-' + header
2431
const headerValue = responseHeaders.get(oldHeaderKey) || ''
2532

26-
requestHeaders.set(header, headerValue)
33+
const oldValue = requestHeaders.get(header) || ''
34+
35+
if (oldValue !== headerValue) {
36+
if (headerValue) {
37+
requestHeaders.set(header, headerValue)
38+
} else {
39+
requestHeaders.delete(header)
40+
}
41+
}
2742
responseHeaders.delete(oldHeaderKey)
2843
}
29-
3044
responseHeaders.delete('x-middleware-override-headers')
3145
}

0 commit comments

Comments
 (0)