Created
September 17, 2024 22:51
-
-
Save treetop1500/fa109da50203aaabb1646ef935e04628 to your computer and use it in GitHub Desktop.
NextJS Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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