Last active
March 29, 2021 20:48
-
-
Save pims/7b0442b5bc881255c93d3d6e4a6e9b3d to your computer and use it in GitHub Desktop.
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
function handleRequest(request) { | |
const NAME = "experiment-0" | |
// The Responses below are placeholders. You can set up a custom path for each test (e.g. /control/somepath ). | |
const TEST_RESPONSE = new Response("Test group") // e.g. await fetch("/test/sompath", request) | |
const CONTROL_RESPONSE = new Response("Control group") // e.g. await fetch("/control/sompath", request) | |
// Determine which group this requester is in. | |
const cookie = request.headers.get("cookie") | |
if (cookie && cookie.includes(`${NAME}=control`)) { | |
return CONTROL_RESPONSE | |
} | |
else if (cookie && cookie.includes(`${NAME}=test`)) { | |
return TEST_RESPONSE | |
} | |
else { | |
// If there is no cookie, this is a new client. Choose a group and set the cookie. | |
const group = Math.random() < 0.5 ? "test" : "control" // 50/50 split | |
const response = group === "control" ? CONTROL_RESPONSE : TEST_RESPONSE | |
response.headers.append("Set-Cookie", `${NAME}=${group}; path=/`) | |
return response | |
} | |
} | |
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment