コンテンツにスキップ

同一URLの直接アクセスによるA/Bテスト

クッキーに基づいて提供されるレスポンスを制御することでA/Bテストを設定します。

このバージョンは、/test/*および/control/*のURIパスに対するリクエストをオリジンサーバーに通過させ、ランダム割り当てをバイパスします。

const NAME = "myExampleABTest";
export default {
async fetch(request) {
// 元のURLをクローンします
const url = new URL(request.url);
// コントロールおよびテストルートへの直接アクセスを許可するためにパススルーを有効にします。
if (url.pathname.startsWith("/control") || url.pathname.startsWith("/test"))
return fetch(request);
// このリクエスターがどのグループに属しているかを判断します。
const cookie = request.headers.get("cookie");
if (cookie && cookie.includes(`${NAME}=control`)) {
url.pathname = "/control" + url.pathname;
} else if (cookie && cookie.includes(`${NAME}=test`)) {
url.pathname = "/test" + url.pathname;
} else {
// クッキーがない場合、これは新しいクライアントです。グループを選択し、クッキーを設定します。
const group = Math.random() < 0.5 ? "test" : "control"; // 50/50の分割
if (group === "control") {
url.pathname = "/control" + url.pathname;
} else {
url.pathname = "/test" + url.pathname;
}
// 不変性を避けるためにレスポンスを再構築します
let response = await fetch(url);
response = new Response(response.body, response);
// 永続的なA/Bセッションを有効にするためにクッキーを設定します。
response.headers.append("Set-Cookie", `${NAME}=${group}; path=/`);
return response;
}
return fetch(url);
},
};