@@ -12,20 +12,34 @@ export const InternalHeaders = {
12
12
// * https://github.com/vercel/next.js/blob/43c9d8940dc42337dd2f7d66aa90e6abf952278e/packages/next/server/web/spec-extension/response.ts#L10-L27
13
13
export function updateModifiedHeaders ( requestHeaders : Headers , responseHeaders : Headers ) {
14
14
const overriddenHeaders = responseHeaders . get ( 'x-middleware-override-headers' )
15
-
16
15
if ( ! overriddenHeaders ) {
17
16
return
18
17
}
19
18
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
+ }
21
28
22
29
for ( const header of headersToUpdate ) {
23
30
const oldHeaderKey = 'x-middleware-request-' + header
24
31
const headerValue = responseHeaders . get ( oldHeaderKey ) || ''
25
32
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
+ }
27
42
responseHeaders . delete ( oldHeaderKey )
28
43
}
29
-
30
44
responseHeaders . delete ( 'x-middleware-override-headers' )
31
45
}
0 commit comments