This might seem quite simple but it took us quite some time to figure out the solution. Hence we decided to share it with the community 🙂
It started with a simple requirement of inserting a security token before every response that goes out of CloudFront (CDN of AWS). Hence the obvious architecture was to intercept the response at viewer_response event and attach it to a Lambda@Edge compute.
But the challenge came while we tried to add a new cookie and ensuring that it does not mess the cookies the origin might be trying to also set.
Here is the code which finally worked:
let finalCookieArray = [];
if(response['headers']['set-cookie']){
for(var cookie of response['headers']['set-cookie']){
finalCookieArray.push(cookie.value);
}
}
finalCookieArray.push(`new-c1=${cookie1}; SameSite=Strict;`);
finalCookieArray.push(`new-c2=${cookie2}; SameSite=Strict;`);
response['headers']['set-cookie'] = [{
'key': 'Set-Cookie',
'value': finalCookieArray
}];
The above code would ensure that whenever the origin is trying to set a cookie, it does not override the header and instead appends the new cookie to the outgoing response.
This technique is useful for user-authentication scenarios, session-timer management, watermark or secure fingerprinting etc.