-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
28 lines (23 loc) · 824 Bytes
/
proxy.ts
File metadata and controls
28 lines (23 loc) · 824 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import jwt from "jsonwebtoken";
const PUBLIC_PATHS = ["/api/auth/login", "/api/auth/register", "/api"];
export function proxy(req: NextRequest) {
if (PUBLIC_PATHS.some((p) => req.nextUrl.pathname.startsWith(p))) {
return NextResponse.next();
}
const authHeader = req.headers.get("authorization");
if (!authHeader)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!);
(req as any).user = decoded;
return NextResponse.next();
} catch {
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
}
export const config = {
matcher: ["/api/:path*"],
};