-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
32 lines (30 loc) · 880 Bytes
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server";
import * as jose from "jose";
export async function middleware(req: NextRequest, res: NextResponse) {
const bearertoken = req.headers.get("authorization") as string;
if (!bearertoken) {
return new NextResponse(
JSON.stringify({ errorMessage: "Unauthorized request" }),
{ status: 401 }
);
}
const token = bearertoken.split(" ")[1];
if (!token) {
return new NextResponse(
JSON.stringify({ errorMessage: "Unauthorized request" }),
{ status: 401 }
);
}
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
try {
await jose.jwtVerify(token, secret);
} catch (error) {
return new NextResponse(
JSON.stringify({ errorMessage: "Unauthorized request" }),
{ status: 401 }
);
}
}
export const config = {
matcher: ["/api/auth/me"],
};