menu
Menu
Mobify DevCenter
search_icon_focus

A/B Testing Using Mobify's Request Processor

Imagine that you want to run an A/B testing experiment where your app responds to different experiment groups.

Let’s use two groups: control for the default handling and experiment for folks that should get the experience we’re testing.

We’ll create a Request Processor that checks whether a user is part of a group from a cookie named ab, then puts the user in a group if they are not in one. The request processor uses setRequestClass to let the app know which group the user is assigned. Here’s the implementation:

const getCookieValueByName = (cookieName, cookieHeader) =>
cookieHeader.replace(
new RegExp(`(?:(?:^|.*;\s*)${cookieName}\s*\=\s*([^;]*).*$)|^.*$`, "g"),
"$1"
)
const assignBucket = () =>
Math.floor(Math.random() * Math.floor(2)) ? "experiment" : "control"
export const processRequest = ({
path,
querystring,
headers,
setRequestClass
}) => {
let group = getCookieValueByName("ab", headers["Cookie"]) || assignBucket()
setRequestClass(`ab=${group}`)
return { path, querystring }
}

Now in pwa/app/ssr.js, we modify render to get the group from the request class using the options argument. We set the ab cookie so its value persists using res.cookie, and then we respond based on the group. For example:

import {createApp, createHandler} from 'progressive-web-sdk/dist/ssr/server/express'
import {render} from 'progressive-web-sdk/dist/ssr/server/react-rendering'
const app = createApp({
//...
})
const getGroupFromRequestClass = requestClass =>
requestClass.split("=").pop() || null
app.get('/*', (req, res) => {
const group = getGroupFromRequestClass(options.requestClass) || 'control'
res.cookie('ab', group)
if (group != 'experiment') {
res.send('Control')
}
res.send('Experiment 🐶🧪')
render(req, res)
})