-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
38 lines (30 loc) · 1.16 KB
/
middleware.ts
File metadata and controls
38 lines (30 loc) · 1.16 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
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { decrypt } from "@actions/sessions";
import { BASE_URL, PROTECTED_ROUTES, PUBLIC_ROUTES } from "@constants/routes";
export default async function middleware(req: NextRequest) {
const { pathname, search } = req.nextUrl;
const isProtectedRoute = PROTECTED_ROUTES.includes(pathname);
const isPublicRoute = PUBLIC_ROUTES.includes(pathname);
const cookie = cookies().get("session")?.value;
const session = await decrypt(cookie);
if (isProtectedRoute && !session) {
let callbackUrl = pathname;
if (search) {
callbackUrl += search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return NextResponse.redirect(
new URL(`/login?callbackUrl=${encodedCallbackUrl}`, req.nextUrl)
);
}
if (isPublicRoute && session) {
const param = new URLSearchParams(search);
const callbackUrl = param.get("callbackUrl");
return NextResponse.redirect(new URL(callbackUrl || BASE_URL, req.nextUrl));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};