-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
48 lines (40 loc) · 1.24 KB
/
middleware.ts
File metadata and controls
48 lines (40 loc) · 1.24 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
46
47
48
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
const PUBLIC_FILE = /\.(.*)$/;
// had to make this again here as the other one is in a file with bcrypt which is not supported on edge runtimes
// NOTE: you can't use every package in here
const verifyJWT = async (jwt) => {
const { payload } = await jwtVerify(
jwt,
new TextEncoder().encode(process.env.JWT_SECRET)
);
return payload;
};
export default async function middleware(req, res) {
const { pathname } = req.nextUrl;
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname.startsWith("/static") ||
pathname.startsWith("/signin") ||
pathname.startsWith("/register") ||
PUBLIC_FILE.test(pathname)
) {
return NextResponse.next();
}
const jwt = req.cookies.get(process.env.COOKIE_NAME);
if (!jwt) {
req.nextUrl.pathname = "/signin";
return NextResponse.redirect(req.nextUrl);
}
try {
await verifyJWT(jwt.value);
return NextResponse.next();
} catch (e) {
console.error(e);
req.nextUrl.pathname = "/signin";
return NextResponse.redirect(req.nextUrl);
}
}
// In most middleware, you'll always use a ".next()" because there's usually
// multiple aspects of middleware involved