Tom
Tom
NNuxt
Created by Tom on 6/10/2024 in #❓・help
Preventing Refetching in Component
No description
6 replies
NNuxt
Created by Tom on 6/10/2024 in #❓・help
Preventing Refetching in Component
https://nuxt.com/docs/getting-started/data-fetching#caching-and-refetching useFetch and useAsyncData use keys to prevent refetching the same data. This was the part that lead be to believe it worked that way.
6 replies
NNuxt
Created by Tom on 6/7/2024 in #❓・help
A/B Testing Middleware
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
6 replies
NNuxt
Created by Tom on 6/7/2024 in #❓・help
A/B Testing Middleware
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.
6 replies
NNuxt
Created by Tom on 6/7/2024 in #❓・help
A/B Testing Middleware
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.
6 replies