import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // Routes only accessible when not authenticated const authRoutes = ['/login', '/register']; export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // Get token from cookies or headers const token = request.cookies.get('auth_token')?.value || request.headers.get('authorization')?.replace('Bearer ', ''); // Check if route is auth route const isAuthRoute = authRoutes.some(route => pathname.startsWith(route)); // If accessing auth routes with token in cookies, redirect to home // Note: We only check cookies here, not localStorage // Client-side protection is handled by the components themselves if (isAuthRoute && token) { return NextResponse.redirect(new URL('/', request.url)); } // Allow all other routes to pass through // Authentication will be handled on the client side by the components // This is necessary because tokens stored in localStorage are not accessible in middleware return NextResponse.next(); } export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) * - public files (public folder) */ '/((?!api|_next/static|_next/image|favicon.ico|.*\\..*|public).*)', ], };