# JavaScript Examples - A/B Testing

Configure an A/B test on Azion's global network by serving one of two responses and remembering each visitor's group in a cookie. Use this pattern to run randomized experiments, such as comparing two page variants, without sending traffic to an origin to decide which version to show.

```js
  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))
  })
```

## How it works

The `fetch` handler reads the incoming `Cookie` header with `request.headers.get("cookie")`. If the visitor already has the test cookie, the function returns the matching variant so their experience stays consistent across requests. For new visitors, `Math.random()` assigns the test or control group at roughly 50/50, and `response.headers.append("Set-Cookie", ...)` persists that choice so the same variant is served next time.

## Related resources

- [JavaScript examples](/en/documentation/devtools/javascript-examples/)
- [Runtime APIs](/en/documentation/products/applications/functions/runtime-apis/javascript/fetch-event/)