const COOKIE_NAME = 'ABTest';
const VALUE_A = 'index-a.html';
const VALUE_B = 'index-b.html';
const BASE_PATH = '/abtest';
async function handleRequest(request) {
const urlInfo = new URL(request.url);
if (!urlInfo.pathname.startsWith(BASE_PATH)) {
return fetch(request);
}
const cookies = new Cookies(request.headers.get('cookie'));
const abTestCookie = cookies.get(COOKIE_NAME);
const cookieValue = abTestCookie?.value;
if (cookieValue === VALUE_A) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}
if (cookieValue === VALUE_B) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}
const testValue = Math.random() < 0.5 ? VALUE_A : VALUE_B;
urlInfo.pathname = `/${BASE_PATH}/${testValue}`;
const response = await fetch(urlInfo.toString());
cookies.set(COOKIE_NAME, testValue, { path: '/', max_age: 60 });
response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;
}
function getSetCookie(cookie) {
const cookieArr = [
`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,
];
const key2name = {
expires: 'Expires',
max_age: 'Max-Age',
domain: 'Domain',
path: 'Path',
secure: 'Secure',
httponly: 'HttpOnly',
samesite: 'SameSite',
};
Object.keys(key2name).forEach(key => {
if (cookie[key]) {
cookieArr.push(`${key2name[key]}=${cookie[key]}`);
}
});
return cookieArr.join('; ');
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
Was this page helpful?