import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // Define public routes that don't require authentication const publicRoutes = [ '/', '/auth/login', '/auth/callback', ]; // Define routes that require admin role const adminRoutes = [ '/admin', ]; export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // Allow access to public routes without authentication if (publicRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`))) { return NextResponse.next(); } // Get the auth token from cookies const token = request.cookies.get('auth_token')?.value; const userRole = request.cookies.get('user_role')?.value; // If no token, redirect to login if (!token) { // Store the original URL to redirect back after login const url = new URL('/auth/login', request.url); url.searchParams.set('callbackUrl', pathname); return NextResponse.redirect(url); } // Check if the route requires admin role if (adminRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`))) { // If not admin role, redirect to dashboard if (userRole !== 'ADMIN') { return NextResponse.redirect(new URL('/dashboard', request.url)); } } return NextResponse.next(); } // Configure the middleware to run on all routes except static files and api routes export const config = { matcher: [ /* * Match all request paths except for: * 1. /api routes * 2. /_next (Next.js internals) * 3. /_static (static files) * 4. /_vercel (Vercel internals) * 5. /favicon.ico, /robots.txt, /sitemap.xml (common static files) */ '/((?!api|_next|_static|_vercel|favicon.ico|robots.txt|sitemap.xml).*)', ], };