Adding a cookie at viewer_response using Lambda@Edge

a simple piece of code, but figuring out the right way to handle cookies was painful !

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 = [];
  for(var cookie of response['headers']['set-cookie']){
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.

about us:

kitsune (

kitsune is a cloud-native framework which enables developers to create full stack serverless web applications without having to worry about architecture, scalability and maintenance. kitsune also provides a HTML based language for developers making it the simplest way to build serverless web apps.