Created
August 10, 2021 09:06
-
-
Save danielreiser/62484eb458611674ecd7ea1fe75f9e37 to your computer and use it in GitHub Desktop.
Viewer Request lambda@edge function
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, context, callback) => { | |
console.group('[INFO] lambda@edge Viewer Request') | |
const request = event.Records[0].cf.request; | |
const latestOriginHash = await ssm.getParameter({ | |
Name: LATEST_ORIGIN_GIT_HASH, | |
WithDecryption: false, | |
}).promise(); | |
const hash = latestOriginHash.Parameter.Value; | |
if (request.headers.cookie) { | |
console.log(request.headers.cookie); | |
const cookieObj = cookieStringToObj(request.headers.cookie[0].value); | |
if (cookieObj.hasOwnProperty(SOURCE_COOKIE_NAME)) { | |
const sourceCookieValue = cookieObj[SOURCE_COOKIE_NAME]; | |
console.log(`Request has source cookie with value: ${sourceCookieValue}`) | |
if (sourceCookieValue !== hash) { | |
console.log(`Source cookie hash (${sourceCookieValue}) is different, update with latest ${hash}.`); | |
cookieObj[SOURCE_COOKIE_NAME] = hash; | |
request.headers.cookie.push({ key: 'Cookie', value: objToCookieString(cookieObj) }); | |
} | |
return request; | |
} | |
} | |
console.log(`NO source cookie found -> cookies: ${JSON.stringify(request.headers.cookie)}, uri: ${request.uri}`); | |
const cookieObj = { [SOURCE_COOKIE_NAME]: hash }; | |
request.headers.cookie = [{ key: 'Cookie', value: objToCookieString(cookieObj) }] | |
console.groupEnd() | |
return request; | |
}; | |
function cookieStringToObj(cookieString) { | |
return Object.fromEntries(cookieString.split(/; *!/).map(c => { | |
const [key, ...v] = c.split('='); | |
return [key, decodeURIComponent(v.join('='))]; | |
})); | |
} | |
function objToCookieString(cookieObj) { | |
return Object.entries(cookieObj).reduce((res, [key, value]) => res += `${key}=${encodeURIComponent(value)}; `, '').trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment