In this example, cookies are used to store session information and perform A/B testing on requests. This example demonstrates how to use an edge function to perform A/B testing.
Sample Code
// cookie name
constCOOKIE_NAME='ABTest';
// cookie value
constVALUE_A='index-a.html';
constVALUE_B='index-b.html';
// Root path, the origin must exist this path, and under this path, there are files index-a.html and index-b.html.
constBASE_PATH='/abtest';
asyncfunctionhandleRequest(request){
const urlInfo =newURL(request.url);
// Judge the URL path, if accessing non-abtest resources, directly responded.
if(!urlInfo.pathname.startsWith(BASE_PATH)){
returnfetch(request);
}
// Collected the current request's Cookie.
const cookies =newCookies(request.headers.get('cookie'));
const abTestCookie = cookies.get(COOKIE_NAME);
const cookieValue = abTestCookie?.value;
// If the Cookie value is A test, Return index-a.html.
if(cookieValue ===VALUE_A){
urlInfo.pathname =`/${BASE_PATH}/${cookieValue}`;
returnfetch(urlInfo.toString());
}
// If the Cookie value is B test, Return index-b.html.
if(cookieValue ===VALUE_B){
urlInfo.pathname =`/${BASE_PATH}/${cookieValue}`;
returnfetch(urlInfo.toString());
}
// If the Cookie information does not exist, randomly grant the current request to A or B test.