-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
41 lines (36 loc) · 1.08 KB
/
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
41
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { cookies } from "next/headers";
import { checkJWTValidity } from "./utils/checkJwtValidity";
export default async function middleware(req: NextRequest) {
// retrieve token from cookies
const cookieStore = cookies();
let token = cookieStore.get("token")?.value;
// check if token exists
if (!token) {
console.error("Token is undefined");
} else {
// check if session is valid
const isAuthenticated = checkJWTValidity(token);
if (!isAuthenticated) {
console.error("Invalid token");
}
}
// list of protected routes
const protectedRoutes = [
"/dashboard",
"/watchlist",
"/settings",
"/stock",
];
// only redirect if the user is trying to access a protected route
if (
protectedRoutes.includes(req.nextUrl.pathname) &&
(!token || !checkJWTValidity(token)) &&
!req.nextUrl.pathname.endsWith(".css") &&
!req.nextUrl.pathname.endsWith(".js")
) {
const absoluteURL = new URL("/", req.nextUrl.origin);
return NextResponse.redirect(absoluteURL.toString());
}
}