Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Pages Functions で A/B テストする

最終更新 Markdown で表示Agent セットアップ

このガイドでは、Pages プロジェクトで Pages Functions を使って A/B テストする方法を学びます。A/B テストは、ウェブページやアプリケーションの 2 つ以上のバージョンを比較するユーザー体験の調査手法です。A/B テストでは、2 つ以上のバージョンのウェブページをユーザーに配信し、サイトへのトラフィックを分割できます。

概要

A/B テスト向けにアプリケーションの複数バージョンを設定する方法は、ユースケースごとに異なります。どの開発者にも共通する、セットアップを簡単にする原則はいくつかあります。

アプリケーションのバージョン数(このガイドでは 2 つ)に応じて、ユーザーを実験グループに割り当てられます。このガイドの実験グループは、ベースルート / とテストルート /test です。

割り当てたグループにユーザーがとどまるように、ブラウザーに Cookie を設定して保存します。設定した Cookie の値に応じて、対応するルートが配信されます。

Pages Function をセットアップする

プロジェクトでは、A/B テストのロジックを Pages Functions で扱えます。Pages Functions を使うと、Pages プロジェクト内からサーバーロジックを扱えます。

次の手順で始めます。

  1. ローカルマシンで Pages プロジェクトのディレクトリを開きます。
  2. /functions ディレクトリを作成します。アプリケーションのサーバーロジックは /functions ディレクトリに置きます。

ミドルウェアのロジックを追加する

Pages Functions には、ルートハンドラーの前や後で実行するロジックの塊を再利用できるユーティリティ関数があります。これが ミドルウェア です。このガイドでは、ミドルウェアでサイトに届く前に Pages プロジェクトへのリクエストを横取りできます。

/functions ディレクトリに _middleware.js ファイルを作成します。

Functions の命名規則に従い、_middleware.js ファイルは requestenvnext を引数に取る単一の async onRequest 関数をエクスポートします。

const abTest = async ({ request, next, env }) => {
	/*
  Todo:
  1. Conditional statements to check for the cookie
  2. Assign cookies based on percentage, then serve
  */
};

export const onRequest = [abTest];

Cookie を設定するには、cookieName 変数を作成して任意の値を割り当てます。次に newHomepagePathName 変数を作成し、/test を割り当てます。

const cookieName = "ab-test-cookie";
const newHomepagePathName = "/test";

const abTest = async ({ request, next, env }) => {
	/*
  Todo:
  1. Conditional statements to check for the cookie
  2. Assign cookie based on percentage then serve
  */
};

export const onRequest = [abTest];

条件分岐を設定する

URL のパス名に基づき、Cookie の値が new と等しいかを確認します。値が new なら、newHomepagePathName が配信されます。

const cookieName = "ab-test-cookie";
const newHomepagePathName = "/test";

const abTest = async ({ request, next, env }) => {
	/*
  Todo:
  1. Assign cookies based on randomly generated percentage, then serve
  */

	const url = new URL(request.url);
	if (url.pathname === "/") {
		// if cookie ab-test-cookie=new then change the request to go to /test
		// if no cookie set, pass x% of traffic and set a cookie value to "current" or "new"

		let cookie = request.headers.get("cookie");
		// is cookie set?
		if (cookie && cookie.includes(`${cookieName}=new`)) {
			// Change the request to go to /test (as set in the newHomepagePathName variable)
			url.pathname = newHomepagePathName;
			return env.ASSETS.fetch(url);
		}
	}
};

export const onRequest = [abTest];

Cookie の値がない場合は、値を割り当てる必要があります。Math.floor(Math.random() * 100) で割合(0〜99)を生成します。デフォルトの Cookie バージョンには current を割り当てます。

生成した数の割合が 50 より小さい場合は、Cookie バージョンを new にします。ランダムに生成した割合に基づいて Cookie を設定し、アセットを配信します。条件ブロックのあと、リクエストを next() に渡します。これによりリクエストが Pages に渡されます。結果として、ユーザーの 50% が /test のホームページを受け取ります。

env.ASSETS.fetch() 関数を使うと、url パラメーターで定義した変更後のパスへユーザーを送れます。env は環境変数とバインディングを含むオブジェクトです。ASSETS は、Function と Pages のアセット配信リソースの通信を可能にするデフォルトの Function バインディングです。fetch() は Pages のアセット配信リソースを呼び出し、アセット(/test ホームページ)をサイトの訪問者に返します。

const cookieName = "ab-test-cookie";
const newHomepagePathName = "/test";

const abTest = async (context) => {
	const url = new URL(context.request.url);
	// if homepage
	if (url.pathname === "/") {
		// if cookie ab-test-cookie=new then change the request to go to /test
		// if no cookie set, pass x% of traffic and set a cookie value to "current" or "new"

		let cookie = request.headers.get("cookie");
		// is cookie set?
		if (cookie && cookie.includes(`${cookieName}=new`)) {
			// pass the request to /test
			url.pathname = newHomepagePathName;
			return context.env.ASSETS.fetch(url);
		} else {
			const percentage = Math.floor(Math.random() * 100);
			let version = "current"; // default version
			// change pathname and version name for 50% of traffic
			if (percentage < 50) {
				url.pathname = newHomepagePathName;
				version = "new";
			}
			// get the static file from ASSETS, and attach a cookie
			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];

Cloudflare Pages にデプロイする

プロジェクトに functions/_middleware.js ファイルを用意したら、Pages でデプロイできます。プロジェクトの変更を GitHub / GitLab にプッシュします。

アプリケーションをデプロイしたら、ミドルウェア Function を確認します。

  1. Cloudflare ダッシュボードで Workers & Pages ページを開きます。

    Workers & Pages を開く ↗
  2. Pages プロジェクト > Settings > Functions > Configuration を選びます。

役に立ちましたか?