Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Created September 17, 2024 22:51
Show Gist options
  • Save treetop1500/fa109da50203aaabb1646ef935e04628 to your computer and use it in GitHub Desktop.
Save treetop1500/fa109da50203aaabb1646ef935e04628 to your computer and use it in GitHub Desktop.
NextJS Middleware
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