Hey,
I’m Trying to configure A/B test with Cloudflare worker.
my route is :
mydomain.com/*
the problem is that the logic runs like 3-5 times [i can see the cookie generating few times for each request]
it runs the code for the page request [html request] and it runs the code also for the image request etc…
I want the code only to perform once for the HTML request.
any suggestions on how to do that?
This is my worker code :
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})
async function fetchAndApply(request) {
const name = 'experiment-0'
let group // 'control' or 'test', set below
let isNew = false // is the group newly-assigned?
// Determine which group this request is in.
const cookie = request.headers.get('Cookie')
if (cookie && cookie.includes(`${name}=control`)) {
group = 'control'
} else if (cookie && cookie.includes(`${name}=test`)) {
group = 'test'
} else {
// 50/50 Split
group = Math.random() < 0.5 ? 'control' : 'test'
isNew = true
}
var response;
if (group == 'test') {
// Force Cloudflare not to cache everything
response = await fetch(request, {
cf: {
cacheEverything: 'True'
}
})
} else {
response = await fetch(request, {
cf: {
cacheEverything: 'False'
}
})
}
if (isNew) {
// The experiment was newly-assigned, so add a Set-Cookie header
// to the response.
const newHeaders = new Headers(response.headers)
newHeaders.append('Set-Cookie', `${name}=${group}`)
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
} else {
// Return response unmodified.
return response
}
}
Thanks,
Max