Perform A/B testing

更新时间:
复制 MD 格式

Edge functions help you quickly perform A/B testing for scenarios such as phased releases or traffic distribution for experimental features. This topic describes how to set up A/B testing by controlling cookie-based responses.

Sample code

  • Result: Performs A/B testing using a single URL.

  • Language: JavaScript

  • Sample code:

    // Determines the user group based on the Cookie header. Different content is returned for different group tags.
    async function handleRequest(request) {
      const NAME = 'var';
      const TEST_RESPONSE = new Response('A group'); // The Response content can also be replaced with the dynamic content of a fetch request.
      const CONTROL_RESPONSE = new Response('B group');
      // Determines the group based on the var field 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';
        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 URL of the edge function or your configured routing address in a browser. If the browser does not have a cookie, a group is randomly selected:

  • 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