-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
58 lines (47 loc) · 1.5 KB
/
middleware.ts
File metadata and controls
58 lines (47 loc) · 1.5 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
51
52
53
54
55
56
57
import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE_NAME } from "@/lib/auth/constants";
import { verifySessionToken } from "@/lib/auth/session";
const PUBLIC_PATHS = new Set([
"/login",
"/api/auth/login",
"/api/auth/logout",
"/favicon.ico",
]);
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (isPublicPath(pathname)) {
if (pathname === "/login") {
const token = request.cookies.get(SESSION_COOKIE_NAME)?.value;
if (token) {
const session = await verifySessionToken(token);
if (session) {
return NextResponse.redirect(new URL("/", request.url));
}
}
}
return NextResponse.next();
}
const token = request.cookies.get(SESSION_COOKIE_NAME)?.value;
if (!token) {
return redirectToLogin(request);
}
const session = await verifySessionToken(token);
if (!session) {
return redirectToLogin(request);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};
function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
return pathname.startsWith("/_next");
}
function redirectToLogin(request: NextRequest): NextResponse {
const loginUrl = new URL("/login", request.url);
if (request.nextUrl.pathname !== "/") {
loginUrl.searchParams.set("next", request.nextUrl.pathname);
}
return NextResponse.redirect(loginUrl);
}