(request: NextRequest)
| 7 | const adminRoutes = ["/admin"]; |
| 8 | |
| 9 | export default async function authMiddleware(request: NextRequest) { |
| 10 | const pathName = request.nextUrl.pathname; |
| 11 | const isAuthRoute = authRoutes.includes(pathName); |
| 12 | const isPasswordRoute = passwordRoutes.includes(pathName); |
| 13 | const isAdminRoute = adminRoutes.includes(pathName); |
| 14 | |
| 15 | const { data: session } = await betterFetch<Session>( |
| 16 | "/api/auth/get-session", |
| 17 | { |
| 18 | baseURL: process.env.BETTER_AUTH_URL, |
| 19 | headers: { |
| 20 | //get the cookie from the request |
| 21 | cookie: request.headers.get("cookie") || "", |
| 22 | }, |
| 23 | }, |
| 24 | ); |
| 25 | |
| 26 | if (!session) { |
| 27 | if (isAuthRoute || isPasswordRoute) { |
| 28 | return NextResponse.next(); |
| 29 | } |
| 30 | return NextResponse.redirect(new URL("/sign-in", request.url)); |
| 31 | } |
| 32 | |
| 33 | if (isAuthRoute || isPasswordRoute) { |
| 34 | return NextResponse.redirect(new URL("/", request.url)); |
| 35 | } |
| 36 | |
| 37 | if (isAdminRoute && session.user.role !== "admin") { |
| 38 | return NextResponse.redirect(new URL("/", request.url)); |
| 39 | } |
| 40 | |
| 41 | return NextResponse.next(); |
| 42 | } |
| 43 | |
| 44 | export const config = { |
| 45 | matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'], |
nothing calls this directly
no outgoing calls
no test coverage detected