Skip to content

Instantly share code, notes, and snippets.

Created February 19, 2018 16:16
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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);
if (requestHeaders.cookie[i].value.indexOf(sourceMainCookie) >= 0) {
console.log('Main Source cookie found');
setCookie(response, sourceMainCookie);
callback(null, response);
// 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 }];
Copy link

Sinale7 commented Mar 27, 2020


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