-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (38 loc) · 1.3 KB
/
middleware.ts
File metadata and controls
46 lines (38 loc) · 1.3 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const authPages = [
"/sign-in",
"/sign-up",
"/forgot-password",
"/email-verification",
"/reset-password",
"/email-verification/new-code",
];
function isAuthenticated(request: NextRequest): boolean {
const token = request.cookies.get("authjs.session-token");
return !!token;
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// If the user is authenticated and trying to access an auth page, redirect to dashboard
if (isAuthenticated(req) && authPages.includes(pathname)) {
return NextResponse.redirect(new URL("/", req.url));
}
// Allow access to profile pages without authentication
if (pathname.startsWith("/profile/") && pathname !== "/profile/edit") {
return NextResponse.next();
}
// If the user is not authenticated and trying to access a protected route, redirect to login
if (
!isAuthenticated(req) &&
!authPages.includes(pathname) &&
!pathname.startsWith("/reset-password/")
) {
return NextResponse.redirect(new URL("/sign-in", req.url));
}
// Otherwise, allow the request to continue
return NextResponse.next();
}
export const config = {
matcher: ["/((?!static|favicon.ico|_next|.*\\..*|api|trpc).*)", "/"],
};