@@ -50,6 +50,19 @@ const CloudFrontBlacklistedHeaders = [
50
50
"x-real-ip" ,
51
51
] ;
52
52
53
+ // Read-only headers, see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-read-only-headers
54
+ // We should only remove these headers when directly responding in lambda@edge , not for the external middleware
55
+ const cloudfrontReadOnlyHeaders = [
56
+ "accept-encoding" ,
57
+ "content-length" ,
58
+ "if-modified-since" ,
59
+ "if-none-match" ,
60
+ "if-range" ,
61
+ "if-unmodified-since" ,
62
+ "transfer-encoding" ,
63
+ "via" ,
64
+ ] ;
65
+
53
66
function normalizeCloudFrontRequestEventHeaders (
54
67
rawHeaders : CloudFrontHeaders ,
55
68
) : Record < string , string > {
@@ -97,14 +110,17 @@ type MiddlewareEvent = {
97
110
98
111
function convertToCloudfrontHeaders (
99
112
headers : Record < string , OutgoingHttpHeader > ,
113
+ directResponse ?: boolean ,
100
114
) {
101
115
const cloudfrontHeaders : CloudFrontHeaders = { } ;
102
116
Object . entries ( headers )
103
117
. filter (
104
118
( [ key ] ) =>
105
119
! CloudFrontBlacklistedHeaders . some ( ( header ) =>
106
120
typeof header === "string" ? header === key : header . test ( key ) ,
107
- ) ,
121
+ ) &&
122
+ // Only remove read-only headers when directly responding in lambda@edge
123
+ ( directResponse ? ! cloudfrontReadOnlyHeaders . includes ( key ) : true ) ,
108
124
)
109
125
. forEach ( ( [ key , value ] ) => {
110
126
if ( key === "set-cookie" ) {
@@ -146,7 +162,7 @@ async function convertToCloudFrontRequestResult(
146
162
const cloudfrontResult = {
147
163
status : externalResult . statusCode . toString ( ) ,
148
164
statusDescription : "OK" ,
149
- headers : convertToCloudfrontHeaders ( externalResult . headers ) ,
165
+ headers : convertToCloudfrontHeaders ( externalResult . headers , true ) ,
150
166
bodyEncoding : externalResult . isBase64Encoded
151
167
? ( "base64" as const )
152
168
: ( "text" as const ) ,
@@ -195,7 +211,7 @@ async function convertToCloudFrontRequestResult(
195
211
const response : CloudFrontRequestResult = {
196
212
status : result . statusCode . toString ( ) ,
197
213
statusDescription : "OK" ,
198
- headers : convertToCloudfrontHeaders ( responseHeaders ) ,
214
+ headers : convertToCloudfrontHeaders ( responseHeaders , true ) ,
199
215
bodyEncoding : result . isBase64Encoded ? "base64" : "text" ,
200
216
body : result . body ,
201
217
} ;
0 commit comments