-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
38 lines (29 loc) · 990 Bytes
/
middleware.ts
File metadata and controls
38 lines (29 loc) · 990 Bytes
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 { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET!;
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
console.log("Middleware hit for:", pathname); // Debug log
const publicPaths = ["/auth", "/blog", "/api", "/favicon.ico"];
// Allow public routes
if (publicPaths.some((path) => pathname.startsWith(path))) {
return NextResponse.next();
}
// Check JWT token in cookies
const token = request.cookies.get("token")?.value;
if (!token) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
try {
jwt.verify(token, JWT_SECRET);
console.log("Token valid, proceeding");
} catch (err) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
return NextResponse.next();
}
// Protect these routes
export const config = {
matcher: [ "/post" ],
};