All Products
Search
Document Center

Edge Security Acceleration:Perform A/B testing

Last Updated:Dec 25, 2025

Edge Routine can help you quickly perform A/B testing in scenarios such as canary releases and traffic distributions for experimental features. This topic describes an example of performing A/B testing by controlling cookie-based responses.

Sample code

  • Result: A/B testing is performed based on direct access to the same URL.

  • Language: JavaScript

  • Sample code:

    // Determines the user group based on the cookie header. Different contents are returned based on group labels.
    async function handleRequest(request) {
      const NAME = 'var';
      const TEST_RESPONSE = new Response('A group'); // You can replace the content of Response with the dynamic content of a fetch request.
      const CONTROL_RESPONSE = new Response('B group');
      // Uses the var field in the cookie to determine the group.
      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, selects a group.    const group = Math.random() < 0.5 ? 'A group' : 'B group';
        const response = group === 'B group' ? CONTROL_RESPONSE : TEST_RESPONSE;
        response.headers.append('Set-Cookie', `${NAME}=${group}; path=/`);
        return response;
      }
    }
    
    export default {
      fetch(request) {
        return handleRequest(request);
      }
    }
    

Deployment result

Visit the routine associated by Edge Routine or the configured routable IP address in a browser. If no cookie exists in the browser, a group is selected randomly:

  • If group A is labeled, the response for group A is returned.image

  • If group B is labeled, the response for group B is returned.image