-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.ts
55 lines (46 loc) · 1.67 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
49
50
51
52
53
54
55
import { withAuth } from "next-auth/middleware";
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Define role-based paths
const rolePaths: Record<string, string> = {
ADMIN: "/dashboard/admin",
EDITOR: "/dashboard/editor",
USER: "/dashboard/user",
};
export default withAuth(
async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Handle caching for /api/public/*
if (pathname.startsWith("/api/public")) {
const response = NextResponse.next();
const cacheControlValue =
process.env.NODE_ENV === "development"
? "no-store"
: "s-maxage=3600, stale-while-revalidate=59";
response.headers.set("Cache-Control", cacheControlValue);
return response;
}
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
// If user is not authenticated, let withAuth handle it (redirect to login)
if (!token) return NextResponse.next();
const userRole = token.role as string;
// Redirect users to their appropriate dashboard if accessing unauthorized routes
if (
pathname.startsWith("/dashboard") &&
!pathname.startsWith(rolePaths[userRole])
) {
return NextResponse.redirect(new URL(rolePaths[userRole], req.url));
}
return NextResponse.next(); // Allow access if everything is valid
},
{
pages: {
signIn: "/login", // Redirect unauthenticated users to login
},
}
);
// Match only the necessary routes
export const config = {
matcher: ["/dashboard/:path*", "/api/public/:path*"], // Apply middleware to /dashboard and /api/public/*
};