-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (38 loc) · 1.27 KB
/
middleware.ts
File metadata and controls
46 lines (38 loc) · 1.27 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 type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { SESSION_COOKIE } from "@/lib/config";
const AUTH_PATH = "/login";
const DASHBOARD_REDIRECT = "/claims";
function isPublicPath(pathname: string) {
return pathname === AUTH_PATH || pathname.startsWith("/_next") || pathname.startsWith("/public") || pathname.startsWith("/favicon");
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname.startsWith("/api")) {
return NextResponse.next();
}
if (isPublicPath(pathname) || pathname === "/") {
if (pathname === AUTH_PATH) {
const token = request.cookies.get(SESSION_COOKIE)?.value;
if (token) {
const url = request.nextUrl.clone();
url.pathname = DASHBOARD_REDIRECT;
return NextResponse.redirect(url);
}
}
return NextResponse.next();
}
const token = request.cookies.get(SESSION_COOKIE)?.value;
if (!token) {
const url = request.nextUrl.clone();
url.pathname = AUTH_PATH;
if (pathname !== "/") {
url.searchParams.set("redirect", pathname);
}
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|api).*)"],
};