-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathmiddleware.ts
More file actions
45 lines (36 loc) · 1.11 KB
/
Copy pathmiddleware.ts
File metadata and controls
45 lines (36 loc) · 1.11 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
import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
const ONBOARDING_PATH = '/onboarding';
const PROTECTED_PREFIXES = ['/dashboard', '/profile', '/onboarding'];
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const token = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
const isProtected = PROTECTED_PREFIXES.some((p) => pathname.startsWith(p));
if (!token && isProtected) {
const login = new URL('/auth/login', req.url);
login.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(login);
}
if (token && pathname.startsWith('/onboarding')) {
return NextResponse.next();
}
if (
token &&
token.emailVerified &&
!token.onboardingCompleted &&
!pathname.startsWith(ONBOARDING_PATH) &&
!pathname.startsWith('/api') &&
isProtected
) {
return NextResponse.redirect(new URL(ONBOARDING_PATH, req.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};