Created
August 10, 2021 09:29
-
-
Save danielreiser/7ff347b85ee4e95a85057bb9cdc995c4 to your computer and use it in GitHub Desktop.
Origin Response lambda@edge function for setting a cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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