Skip to content

Instantly share code, notes, and snippets.

@danielreiser
Created August 10, 2021 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielreiser/7ff347b85ee4e95a85057bb9cdc995c4 to your computer and use it in GitHub Desktop.
Save danielreiser/7ff347b85ee4e95a85057bb9cdc995c4 to your computer and use it in GitHub Desktop.
Origin Response lambda@edge function for setting a cookie
'use strict';
const AWS = require('aws-sdk');
const ssm = new AWS.SSM({ region: 'eu-central-1' });
const SOURCE_COOKIE_NAME = 'myapp-origin';
const LATEST_ORIGIN_GIT_HASH = 'myapp_latest-origin-git-hash';
exports.handler = async event => {
console.group('[INFO] lambda@edge Origin Response')
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
const latestOriginHash = await ssm.getParameter({
Name: LATEST_ORIGIN_GIT_HASH,
WithDecryption: false,
}).promise();
const hash = latestOriginHash.Parameter.Value;
console.log(`Latest git hash is ${hash}`);
if (request.headers.cookie) {
for (let i = 0; i < request.headers.cookie.length; i++) {
if (request.headers.cookie[i].value.indexOf(SOURCE_COOKIE_NAME) >= 0) {
console.log(`Source cookie found. ${request.headers.cookie[i].value}`);
setCookie(response, hash);
}
}
} else {
console.log('No Source cookie found');
}
console.log(request.headers['cache-control'])
console.groupEnd()
return response;
};
// Add set-cookie header (including path)
const setCookie = function (response, cookieValue) {
const cookiePath = '/';
const cookie = `${SOURCE_COOKIE_NAME}=${cookieValue}; Path=${cookiePath}; SameSite=None; Secure;`;
console.log(`Setting cookie ${cookie}`);
response.headers['set-cookie'] = [{ key: 'Set-Cookie', value: cookie }];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment