コンテンツにスキップ

ミドルウェアを使用したA/Bテスト

クッキーに基づいて提供されるページを制御することでA/Bテストを設定します。 このバージョンは、リクエストをテストとコントロールのために オリジンに渡すことをサポートしています。

const cookieName = "ab-test-cookie"
const newHomepagePathName = "/test"
const abTest = async (context) => {
const url = new URL(context.request.url)
// ホームページの場合
if (url.pathname === "/") {
// クッキー ab-test-cookie=new が設定されている場合、リクエストを /test に変更
// クッキーが設定されていない場合、x%のトラフィックを渡し、クッキー値を "current" または "new" に設定
let cookie = request.headers.get("cookie")
// クッキーは設定されていますか?
if (cookie && cookie.includes(`${cookieName}=new`)) {
// リクエストを /test に渡す
url.pathname = newHomepagePathName
return context.env.ASSETS.fetch(url)
} else {
const percentage = Math.floor(Math.random() * 100)
let version = "current" // デフォルトバージョン
// トラフィックの50%のためにパス名とバージョン名を変更
if (percentage < 50) {
url.pathname = newHomepagePathName
version = "new"
}
// ASSETSから静的ファイルを取得し、クッキーを添付
const asset = await context.env.ASSETS.fetch(url)
let response = new Response(asset.body, asset)
response.headers.append("Set-Cookie", `${cookieName}=${version}; path=/`)
return response
}
}
return context.next()
};
export const onRequest = [abTest];