tencent cloud

Tencent Cloud EdgeOne

ABテスト

ダウンロード
フォーカスモード
フォントサイズ
最終更新日: 2026-10-15 18:25:50
AI翻訳
この例ではCookieを使用してセッション情報を保存し、リクエストに対してA/Bテスト制御を行います。エッジ関数を使用してA/Bテストのシナリオを実装しています。

サンプルコード

// cookie 名
const COOKIE_NAME = 'ABTest';

// cookie 値
const VALUE_A = 'index-a.html';
const VALUE_B = 'index-b.html';

// ルートパス。オリジンサーバーにこのパスが存在し、かつこのパスの下にファイルindex-a.html、index-b.htmlが存在する必要があります。
const BASE_PATH = '/abtest';

async function handleRequest(request) {
const urlInfo = new URL(request.url);

// urlパスを判定し、abtest以外のリソースにアクセスした場合は、直接レスポンスを返します。
if (!urlInfo.pathname.startsWith(BASE_PATH)) {
return fetch(request);
}

// 現在のリクエストのcookieを取得します。
const cookies = new Cookies(request.headers.get('cookie'));
const abTestCookie = cookies.get(COOKIE_NAME);
const cookieValue = abTestCookie?.value;

// cookie値がAテストの場合、index-a.htmlを返します。
if (cookieValue === VALUE_A) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}

// cookie値がBテストの場合、index-b.htmlを返します。
if (cookieValue === VALUE_B) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}

// cookie情報が存在しない場合、現在のリクエストをランダムにAまたはBテストに振り分けます。
const testValue = Math.random() < 0.5 ? VALUE_A : VALUE_B;
urlInfo.pathname = `/${BASE_PATH}/${testValue}`;

const response = await fetch(urlInfo.toString());

cookies.set(COOKIE_NAME, testValue, { path: '/', max_age: 60 });
response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;
}

// Set-Cookieを連結します。
function getSetCookie(cookie) {
const cookieArr = [
`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,
];

const key2name = {
expires: 'Expires',
max_age: 'Max-Age',
domain: 'Domain',
path: 'Path',
secure: 'Secure',
httponly: 'HttpOnly',
samesite: 'SameSite',
};

Object.keys(key2name).forEach(key => {
if (cookie[key]) {
cookieArr.push(`${key2name[key]}=${cookie[key]}`);
}
});

return cookieArr.join('; ');
}

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

サンプルプレビュー

ブラウザのアドレスバーにエッジ関数のトリガールールに一致するURLを入力すると、サンプル効果をプレビューできます。




関連参考

ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック