-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmiddleware.ts
More file actions
57 lines (45 loc) · 1.83 KB
/
middleware.ts
File metadata and controls
57 lines (45 loc) · 1.83 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { NextRequestWithAuth, withAuth } from 'next-auth/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { Experiment, ExperimentVariant } from './utils/experiment';
function getExperimentVariant(request: NextRequest): string {
// Check if user already has an experiment assignment
const existingVariant = request.cookies.get(Experiment.HomepageExperiment);
if (existingVariant?.value) {
return existingVariant.value;
}
// Assign new variant (50/50 split)
// NOSONAR - Math.random is safe for A/B test assignment (non-security context)
const variant = Math.random() < 0.5 ? ExperimentVariant.A : ExperimentVariant.B;
return variant;
}
function setExperimentCookie(response: NextResponse, variant: string): void {
const expirationDate = new Date(Date.now() + 1 * 24 * 60 * 60 * 1000); // 1 day in milliseconds
response.cookies.set(Experiment.HomepageExperiment, variant, {
expires: expirationDate,
secure: process.env.NEXT_PUBLIC_VERCEL_ENV !== undefined,
sameSite: 'lax',
path: '/',
});
}
// Main middleware function
export function middleware(request: NextRequest) {
// Only apply A/B testing to the homepage for logged-out users
if (request.nextUrl.pathname === '/') {
const variant = getExperimentVariant(request);
const response = NextResponse.next();
// Set experiment cookie
setExperimentCookie(response, variant);
// Add experiment variant to headers for client-side access
response.headers.set('x-homepage-experiment', variant);
return response;
}
// For protected routes, use auth middleware
return withAuth(request as NextRequestWithAuth, {
callbacks: {
authorized: ({ token }) => !!token,
},
});
}
export const config = {
matcher: ['/', '/notebook/:path*', '/notebook/api/:path*', '/referral', '/lists', '/list/:path*'],
};