-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
40 lines (34 loc) · 1.35 KB
/
middleware.ts
File metadata and controls
40 lines (34 loc) · 1.35 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(req: NextRequest) {
const token = await getToken({ req });
const path = req.nextUrl.pathname;
if (!token) {
if (path === "/login") {
// Prevent infinite redirect to login
return NextResponse.next();
}
return NextResponse.redirect(new URL("/login", req.url));
}
if (token && path === "/login") {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
// If onboarding is not finished and user is trying to access dashboard, redirect to onboarding
if (token.firstTimeUser && path.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/signup/name", req.url));
}
// If onboarding is finished and user is trying to access the onboarding pages, redirect to dashboard
if (
!token.firstTimeUser &&
(path.startsWith("/signup/name") ||
path.startsWith("/signup/role") ||
path.startsWith("/signup/finish"))
) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/signup/name", "/signup/role", "/signup/finish", "/login"],
};