-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (44 loc) · 1.38 KB
/
middleware.ts
File metadata and controls
50 lines (44 loc) · 1.38 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
import { cookies } from "next/headers";
import { type NextRequest } from "next/server";
import {
apiAuthPrefix,
authRoutes,
DEFAULT_LOGIN_REDIRECT,
publicRoutes,
resetPasswordRoutes,
} from "./routes";
// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
const cookieStore = cookies();
const accessToken = cookieStore.get("accessToken");
const { nextUrl } = req;
const { pathname } = nextUrl;
const isLoggedIn = accessToken?.value;
const isApiAuth = pathname.startsWith(apiAuthPrefix);
const isPasswordResetPath = pathname.startsWith(resetPasswordRoutes);
const isPublicPath = publicRoutes.includes(pathname);
const isAuthPath = authRoutes.includes(pathname);
if (isApiAuth || isPasswordResetPath) return null;
if (isAuthPath) {
if (isLoggedIn) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return null;
}
if (!isLoggedIn && !isPublicPath) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return null;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico|.*\\.png$).*)",
],
};