NuxtN
Nuxtβ€’2y ago
Tom

A/B Testing Middleware

Hello everyone,

I'm wanting to do some A/B Testing on Vercel. The guide is for NextJS (https://vercel.com/blog/ab-testing-with-nextjs-and-vercel#experimenting-at-the-edge).

So I'm looking to convert this into Nuxt, the only thing I can't seem to find any information on is how to set a cookie in a Nuxt Middleware. I've attempted to use
useCookie()
.
Solution
Okay so I've found a solution:
/middleware/ab-test.global.ts

const COOKIE_NAME = "ab_variant";
const THRESHOLD = 0.5;

export default defineNuxtRouteMiddleware((to, from) => {
  const variant = useCookie(COOKIE_NAME);

  if (!variant.value) {
    variant.value = Math.random() <= THRESHOLD ? "a" : "b";
  }

  if (!useVariant().value) {
    useVariant().value = variant.value;
  }
});

Then
composables/useVariant.ts

export const useVariant = () => useState("variant");


I'm unsure whether this is the best solution, but it seems to be working and SSR friendly in my tests.
Was this page helpful?