-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
40 lines (36 loc) · 929 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
33
34
35
36
37
38
39
40
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 token doesn't exists
if (!bearerToken) {
return new NextResponse(
JSON.stringify({
errorMessage: "Unauthorized Request",
}),
{
status: 401,
}
);
}
// get token
const token = bearerToken.split(" ")[1];
// * VERIFY TOKEN
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,
}
);
}
}
// this middleware will be called on if we go to the given route
export const config = {
matcher: ["/api/auth/me"],
};