-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (29 loc) · 1.21 KB
/
middleware.ts
File metadata and controls
42 lines (29 loc) · 1.21 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
// export { auth as middleware } from "@/auth";
import { NextRequest, NextResponse } from "next/server";
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";
import { LOGIN, PROTECTED_SUBROUTES, PUBLIC_ROUTES, ROOT } from "./lib/route";
const { auth } = NextAuth(authConfig);
export const middleware = async (request: NextRequest) => {
const { nextUrl } = request;
// Bypass middleware for NextAuth API routes
if (nextUrl.pathname.startsWith("/api/auth/")) {
console.log("Skipping middleware for NextAuth route:", nextUrl.pathname);
return NextResponse.next();
}
const session = await auth();
const isAuthenticated = !!session?.user || true;
console.log("isAuthenticated", isAuthenticated, nextUrl.pathname);
const isPublicRoutes =
PUBLIC_ROUTES.find(
(route) =>
nextUrl.pathname.startsWith(route) || nextUrl.pathname === ROOT,
) && !PROTECTED_SUBROUTES.find((route) => nextUrl.pathname.includes(route));
console.log("isPublicRoutes", isPublicRoutes);
if (!isPublicRoutes && !isAuthenticated) {
return NextResponse.redirect(new URL(LOGIN, nextUrl));
}
};
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};