以下示例展示了如何根据用户请求中的 Cookie 请求头判断用户属于测试组或对照组,并进行 A/B 测试。
addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) function handleRequest(request) { const NAME = "experiment-0" const TEST_RESPONSE = new Response("Test group") const CONTROL_RESPONSE = new Response("Control group") 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 { 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 } }