N
Nuxtβ€’4mo 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 ```js const COOKIE_NAME = "ab_variant"; const THRESHOLD = 0.5;...
Jump to solution
4 Replies
Tom
Tomβ€’4mo ago
It seems there is /middleware and /server/middleware I'm not entirely sure of the difference but I've come up:
const COOKIE_NAME = "ab_variant";
const THRESHOLD = 0.5;

export default defineEventHandler((event) => {
const variant =
getCookie(event, COOKIE_NAME) || (Math.random() <= THRESHOLD ? "a" : "b");

if (!getCookie(event, COOKIE_NAME)) setCookie(event, COOKIE_NAME, variant);
});
const COOKIE_NAME = "ab_variant";
const THRESHOLD = 0.5;

export default defineEventHandler((event) => {
const variant =
getCookie(event, COOKIE_NAME) || (Math.random() <= THRESHOLD ? "a" : "b");

if (!getCookie(event, COOKIE_NAME)) setCookie(event, COOKIE_NAME, variant);
});
Then:
<script setup lang="ts">
const variant = useCookie("ab_variant");

console.log(variant.value);
</script>
<script setup lang="ts">
const variant = useCookie("ab_variant");

console.log(variant.value);
</script>
Which works, okay, but on the initial load when it sets the cookie I'm getting a Hydration text content mismatch refreshing after that works as expected.
Solution
Tom
Tomβ€’4mo ago
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;
}
});
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");
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.
harlan
harlanβ€’4mo ago
lgtm πŸ‘
Tom
Tomβ€’4mo ago
Pretty simple in the end and is much less code that Next. It actually makes plenty of sense but I had it in my head that useCookie was not accessible inside defineNuxtRouteMiddleware, I limited myself from the very beginning πŸ˜… turns out I was just missing the .global
Want results from more Discord servers?
Add your server