import NextAuth from 'next-auth'; import { authConfig } from './lib/auth.config'; // Edge-runtime middleware. Uses the edge-safe authConfig (no Credentials // provider, no Prisma) — it only validates and refreshes the JWT cookie. The // full auth config with the Credentials provider lives in lib/auth.ts and // runs in the Node.js runtime via the route handlers. const { auth } = NextAuth(authConfig); export default auth((req) => { const isLoggedIn = !!req.auth?.user; // AUTH_DEV_AUTOLOGIN bypasses the picker redirect — resolveUser() handles // the autologin fallback server-side; the middleware just stays out of the way. const isAutologin = process.env['AUTH_DEV_AUTOLOGIN'] === 'true'; const { pathname } = req.nextUrl; // On the picker itself: skip if already logged in. if (pathname === '/select-operator') { if (isLoggedIn) { return Response.redirect(new URL('/', req.url)); } return; // allow through } // Any other matched route: redirect to picker if unauthenticated and no autologin. if (!isLoggedIn && !isAutologin) { return Response.redirect(new URL('/select-operator', req.url)); } }); export const config = { matcher: [ // Run on every path except static assets, image optimization, and the // PWA manifest. The Auth.js / tRPC API routes are excluded explicitly // because they handle session resolution themselves. '/((?!api/auth|api/trpc|_next/static|_next/image|favicon.ico|manifest.webmanifest|icon-.*\\.svg).*)', ], };