Created
October 6, 2019 22:29
-
-
Save projected1/aa42dbf9972b331eb0edfe3b98e1f194 to your computer and use it in GitHub Desktop.
A/B Testing AWS Lambda@Edge demo.
This file contains hidden or 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
/** | |
* A/B Testing AWS Lambda@Edge demo. | |
* | |
* Serves content from server hosts, based on an A/B Testing | |
* header value. | |
* | |
* NOTE: For every new request, an A/B Testing header is added | |
* and a test value is selected and set. This header should | |
* be returned in the response and cached by the client, so | |
* it can be re-submitted with every consecutive API request. | |
*/ | |
'use strict'; | |
// Lambda entry point | |
exports.handler = (event, context, callback) => { | |
// Get the HTTP request headers | |
const request = event.Records[0].cf.request; | |
const headers = request.headers; | |
// Check for an A/B Testing header | |
let abHeader = headers['x-ab-testing']; | |
// If there is none, pick an test value and add the header | |
if (!abHeader) { | |
headers['x-ab-testing'] = [{ | |
key: 'X-AB-Testing', | |
value: Math.random() < 0.7 ? 'A' : 'B' | |
}]; | |
abHeader = headers['x-ab-testing']; | |
} | |
// Route the traffic to the correct server | |
const abValue = abHeader[0].value; | |
switch (abValue) { | |
case 'A': | |
headers.host[0].value = 'a.example.com'; | |
break; | |
case 'B': | |
headers.host[0].value = 'b.example.com'; | |
break; | |
default: | |
throw new Error(`Unsupported A/B Testing value: ${abValue}`); | |
} | |
// Propagate the request | |
callback(null, request); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment