forked from vercel/nextjs-optimizely-experimentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
36 lines (29 loc) · 1.11 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { unstable_precompute as precompute } from "@vercel/flags/next";
import { precomputeFlags } from "./lib/flags";
export const config = {
matcher: ["/", "/product/:path*", "/cart", "/success"],
};
export async function middleware(request: NextRequest) {
let response = NextResponse.next();
const context = {
/* pass context on whatever your flag will need */
};
// decide precompute flags for the homepage only
if (request.nextUrl.pathname === "/") {
const code = await precompute(precomputeFlags, context);
// rewrites the request to the variant for this flag combination
const nextUrl = new URL(
`/${code}${request.nextUrl.pathname}${request.nextUrl.search}`,
request.url
);
response = NextResponse.rewrite(nextUrl, { request });
}
// set a shopper cookie if one doesn't exist or has been cleared
if (!request.cookies.has("shopper")) {
const newShopperId = Math.random().toString(36).substring(2);
response.cookies.set("shopper", newShopperId);
}
return response;
}