forked from Northgate-Systems/RemitX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
55 lines (48 loc) · 1.39 KB
/
Copy pathmiddleware.ts
File metadata and controls
55 lines (48 loc) · 1.39 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyToken } from "@/lib/jwt";
const publicPaths = [
"/",
"/login",
"/api/auth/login",
"/api/auth/register",
"/_next/",
"/favicon.ico",
];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow public paths
if (publicPaths.some((p) => pathname.startsWith(p))) {
return NextResponse.next();
}
// Check for session cookie
const token = request.cookies.get("remitx_session")?.value;
if (!token) {
// Redirect to login for page routes, return 401 for API routes
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 }
);
}
return NextResponse.redirect(new URL("/login", request.url));
}
const payload = verifyToken(token);
if (!payload) {
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 }
);
}
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
// Apply to all routes except static files
"/((?!static|public|_next/static|_next/image|.*\\.png$|.*\\.svg$|.*\\.jpg$|.*\\.ico$|.*\\.css$|.*\\.js$).*)",
"/api/:path*",
],
};