-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
39 lines (32 loc) · 1.11 KB
/
middleware.ts
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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { ROUTES } from "@/constants/common";
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|fonts|images).*)"],
};
export function middleware(request: NextRequest) {
const token = getTokenFromCookies(request);
const currentPath = request.nextUrl.pathname;
const url = request.nextUrl.clone();
if (!token && ROUTES.AUTH_REQUIRED.includes(currentPath)) {
url.pathname = "/signin";
return NextResponse.redirect(url);
}
if (token && ROUTES.NON_AUTH_ACCESSIBLE.includes(currentPath)) {
url.pathname = "/";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
function getTokenFromCookies(request: NextRequest) {
const cookiesHeader = request.headers.get("cookie");
if (!cookiesHeader) return null;
const cookiesArray: [string, string][] = cookiesHeader
.split("; ")
.map((cookie) => {
const [key, value] = cookie.split("=");
return [key, value];
});
const cookies = new Map(cookiesArray);
return cookies.get("accessToken");
}