1 of 20
2 of 20
3 of 20
4 of 20
5 of 20
6 of 20
7 of 20
8 of 20
9 of 20
10 of 20
11 of 20
12 of 20
13 of 20
14 of 20
15 of 20
16 of 20
17 of 20
18 of 20
19 of 20
20 of 20

doc

A/B testing

Configure an A/B test by regulating the type of response based on cookies. Useful for randomized experiments with two variants.A/B testing

  function handleRequest(request) {
    const NAME = "TestA/B"
    const TEST_RESPONSE = new Response("Cookie A")
    const CONTROL_RESPONSE = new Response("Cookie B")
  
    const cookie = request.headers.get("cookie")
    if (cookie && cookie.includes(`${NAME}=a`)) {
      return CONTROL_RESPONSE
    }
    else if (cookie && cookie.includes(`${NAME}=b`)) {
      return TEST_RESPONSE
    }
    else {
      const group = Math.random() < 0.5 ? "test" : "control"
      const response = group === "control" ? CONTROL_RESPONSE : TEST_RESPONSE
      response.headers.append("Set-Cookie", `${NAME}=${group}; path=/`)
  
      return response
    }
  }
  
  addEventListener("fetch", event => {
    event.respondWith(handleRequest(event.request))
  })

Didn’t find what you were looking for? Open a support ticket.