import { auth } from "@/auth"; import { NextResponse } from "next/server"; export const middleware = auth((req) => { const { pathname } = req.nextUrl; const isAuthenticated = !!req.auth; // Protect /api/* except /api/auth/* and /api/health if (pathname.startsWith("/api/")) { const isAuthRoute = pathname.startsWith("/api/auth/"); const isHealthRoute = pathname === "/api/health"; if (!isAuthRoute && !isHealthRoute && !isAuthenticated) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } return NextResponse.next(); } // Redirect authenticated users away from /login and /register if (isAuthenticated && (pathname === "/login" || pathname === "/register")) { return NextResponse.redirect(new URL("/app", req.nextUrl.origin)); } // Protect /app/* routes — redirect unauthenticated users to /login if (pathname.startsWith("/app") && !isAuthenticated) { return NextResponse.redirect(new URL("/login", req.nextUrl.origin)); } return NextResponse.next(); }); export const config = { matcher: [ /* * Match all request paths except: * - _next/static (static files) * - _next/image (image optimisation) * - favicon.ico / favicon.png / favicon.svg * - public assets (top-level files that are not pages) */ "/((?!_next/static|_next/image|favicon\\.ico|favicon\\.png|favicon\\.svg).*)", ], };