-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (36 loc) · 1.19 KB
/
Copy pathmiddleware.ts
File metadata and controls
46 lines (36 loc) · 1.19 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
/**
* Next.js Middleware
* Protects dashboard routes and redirects unauthenticated users
*/
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyToken } from "./lib/server/auth";
// Force Node.js runtime (required for jsonwebtoken)
export const runtime = "nodejs";
const COOKIE_NAME = "moneta-auth-token";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Get token from cookies
const token = request.cookies.get(COOKIE_NAME)?.value;
// Check if accessing dashboard routes
if (pathname.startsWith("/dashboard")) {
if (!token || !verifyToken(token)) {
const url = request.nextUrl.clone();
url.pathname = "/auth/login";
url.searchParams.set("redirect", pathname);
return NextResponse.redirect(url);
}
}
// Check if accessing auth routes while logged in
if (pathname.startsWith("/auth/")) {
if (token && verifyToken(token)) {
const url = request.nextUrl.clone();
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/auth/:path*"],
};