-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
48 lines (40 loc) · 1.42 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
42
43
44
45
46
47
48
import { NextRequest, NextResponse } from "next/server";
import { decrypt } from "@/utils/authentication";
import { cookies } from "next/headers";
// 1. Specify Protected & Public Routes
const protectedRoutes = ["/dashboard"];
const publicRoutes = ["/login", "/register", "/mood", "/session"];
const middleware = async (req: NextRequest) => {
// 2. Check if the current Route is Protected or Public
const path = req.nextUrl.pathname;
const isProtectedRoute = protectedRoutes.includes(path);
const isPublicRoute = publicRoutes.includes(path);
// 3. Decrypt the Session from the Cookie
const cookie = cookies().get("session")?.value;
const sessionValues = await decrypt(cookie);
// 5. Redirect to /login if the user is not authenticated
if (
isProtectedRoute &&
(!sessionValues?.userName ||
!sessionValues?.mood ||
!sessionValues?.session)
) {
return NextResponse.redirect(new URL("/login", req.nextUrl));
}
// 6. Redirect to /dashboard if the user is authenticated
if (
isPublicRoute &&
sessionValues?.name &&
sessionValues?.mood &&
sessionValues?.session &&
!req.nextUrl.pathname.startsWith("/dashboard")
) {
return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
}
return NextResponse.next();
};
// Routes Middleware should not run on
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};
export default middleware;