import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; import { auth } from './lib/auth'; // Paths that don't require authentication const publicPaths = ['/api/auth', '/api/health', '/login', '/favicon.ico']; // Skip authentication for local development const skipAuth = process.env.NEXT_PUBLIC_SKIP_AUTH === 'true'; export default async function proxy(request: NextRequest) { const { pathname } = request.nextUrl; // Skip authentication check for public paths if (publicPaths.some((path) => pathname.startsWith(path))) { return NextResponse.next(); } // Skip authentication entirely in dev mode if (skipAuth) { const response = NextResponse.next(); response.headers.set('x-user-id', 'mock-user-id'); response.headers.set('x-user-email', 'dev@localhost'); return response; } // Check session const session = await auth.api.getSession({ headers: request.headers, }); // If no session, redirect to login if (!session) { // Redirect to login page (not directly to Microsoft) const loginUrl = new URL('/login', request.url); loginUrl.searchParams.set('callbackUrl', pathname); return NextResponse.redirect(loginUrl); } // Add user information to headers (optional) const response = NextResponse.next(); response.headers.set('x-user-id', session.user.id); response.headers.set('x-user-email', session.user.email || ''); return response; } // Configuration - which paths the middleware should run on export const config = { matcher: [ /* * Match all request paths except: * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) * - public folder */ '/((?!_next/static|_next/image|favicon.ico|public).*)', ], };