This topic provides sample code that shows how to perform A/B testing.

Sample code

async function handleRequest(request) {
  const NAME = "var"

  const TEST_RESPONSE=new Response("A group") // You can replace the content of the response with the dynamic content that is requested by calling the fetch API operation.
  const CONTROL_RESPONSE = new Response("B group")
  // Determine the group to which the request belongs based on the value of the var field that is contained in the cookie.
  const cookie = request.headers.get("cookie")
  if (cookie && cookie.includes(`${NAME}=B group`)) {
    return CONTROL_RESPONSE
  }
  else if (cookie && cookie.includes(`${NAME}=A group`)) {
    return TEST_RESPONSE
  }
  else {
    // If no cookie exists, select a group.
    const group = Math.random() < 0.5 ? "A group" : "B group" // Random bucket.
    const response = group === "B group" ? CONTROL_RESPONSE : TEST_RESPONSE
    response.headers.append("Set-Cookie", `${NAME}=${group}; path=/`)

    return response
  }
}

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

Result

The grouping result is returned based on the request-based buckets.

Example 7