A/B test with worker - executing multiple times


#1

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


#2

bump - we still looking for answer.
any suggestions will be welcome.


#3

Hi! I think you want to check if the Content-Type header in the response is text/html before you add the Set-Cookie header. You could also check if the path is the root.


#4

Hey Zack ,
Thank you for you response i found the problem. the route I configured was incorrect. and thats why the test was executed multiple times.

my route was :
ON : mywebsite.com/* [without any off route]

how i fixed it :
OFF : mywebsite.com/wp* [added off route]