Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Created August 20, 2024 21:12
Show Gist options
  • Save treetop1500/d4b5db11224dee465dde486710889e77 to your computer and use it in GitHub Desktop.
Save treetop1500/d4b5db11224dee465dde486710889e77 to your computer and use it in GitHub Desktop.
NextJS Middleware Javascript
import { NextResponse } from 'next/server';
export const config = {
matcher: ['/'],
};
const THRESHOLD = 0.5;
const COOKIE_NAME = 'tm_var';
export function middleware(req) {
const variant = req.cookies.get(COOKIE_NAME) || (Math.random() < THRESHOLD ? 'new' : 'old');
const url = req.nextUrl.clone();
if (variant.value === 'new' || variant === 'new') {
url.pathname = '/index-new';
}
const res = NextResponse.rewrite(url);
if (!req.cookies.get(COOKIE_NAME)) {
res.cookies.set(COOKIE_NAME, variant, { path: '/' });
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment