Skip to content

Instantly share code, notes, and snippets.

@nicusX
Created February 19, 2018 16:16
Show Gist options
  • Save nicusX/74366c4dbd0342c4f441b2e059f1815b to your computer and use it in GitHub Desktop.
Save nicusX/74366c4dbd0342c4f441b2e059f1815b to your computer and use it in GitHub Desktop.
Lambda@Edge A/B testing - Origin Response
'use strict';
const sourceCoookie = 'X-Source';
const sourceMain = 'main';
const sourceExperiment = 'experiment';
const cookiePath = '/';
// Origin Response handler
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const requestHeaders = request.headers;
const response = event.Records[0].cf.response;
const sourceMainCookie = `${sourceCoookie}=${sourceMain}`;
const sourceExperimenCookie = `${sourceCoookie}=${sourceExperiment}`;
// Look for Source cookie
// A single cookie header entry may contains multiple cookies, so it looks for a partial match
if (requestHeaders.cookie) {
for (let i = 0; i < requestHeaders.cookie.length; i++) {
// ...ugly but simple enough for now
if (requestHeaders.cookie[i].value.indexOf(sourceExperimenCookie) >= 0) {
console.log('Experiment Source cookie found');
setCookie(response, sourceExperimenCookie);
callback(null, response);
return;
}
if (requestHeaders.cookie[i].value.indexOf(sourceMainCookie) >= 0) {
console.log('Main Source cookie found');
setCookie(response, sourceMainCookie);
callback(null, response);
return;
}
}
}
// If request contains no Source cookie, do nothing and forward the response as-is
console.log('No Source cookie found');
callback(null, response);
}
// Add set-cookie header (including path)
const setCookie = function(response, cookie) {
const cookieValue = `${cookie}; Path=${cookiePath}`;
console.log(`Setting cookie ${cookieValue}`);
response.headers['set-cookie'] = [{ key: "Set-Cookie", value: cookieValue }];
}
@Sinale7
Copy link

Sinale7 commented Mar 27, 2020

Hi,

Thanks for your amazing code !
However, I have an issue with the line 46 when I test it with a cookie (X-Source=main or X-Source=experiment)

Here is the error detail :
Invoke Error {"errorType":"TypeError","errorMessage":"Cannot read property 'headers' of undefined","stack":["TypeError: Cannot read property 'headers' of undefined"," at setCookie

Do you know where it comes from ? Thanks a lot :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment