/** * * @description This page represent the middleware which contain the function * that stay between the request and the source , it filter them and do what must be do * for example it protect the must to be user api routes * * source : https://nextjs.org/docs/app/building-your-application/routing/middleware */ import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; import { verifyToken } from '@/lib/auth'; // Define protected API routes const protectedApiRoutes = [ '/api/user', // Add other protected API routes here ]; // Define public routes that don't require authentication const publicRoutes = [ '/login', '/register', '/forgot-password', '/api/auth', '/api/auth/verify', // Add other public routes here ]; export async function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // Skip middleware for public routes if (publicRoutes.some(route => pathname.startsWith(route))) { return NextResponse.next(); } // Check if the request is for a protected API route const isProtectedApiRoute = protectedApiRoutes.some(route => pathname.startsWith(route)); if (isProtectedApiRoute) { try { // Verify the token const token = request.cookies.get('authToken')?.value; if (!token) { return NextResponse.json( { success: false, message: 'No token provided' }, { status: 401 } ); } const isValid = await verifyToken(token); if (!isValid) { return NextResponse.json( { success: false, message: 'Invalid or expired token' }, { status: 401 } ); } // Token is valid, continue with the request return NextResponse.next(); } catch (error) { console.error('Authentication error:', error); return NextResponse.json( { success: false, message: 'Authentication failed' }, { status: 500 } ); } } // For non-API routes, check if user is authenticated const isAuthenticated = await verifyToken(request.cookies.get('authToken')?.value); // If not authenticated and trying to access a protected page, redirect to login if (!isAuthenticated && !pathname.startsWith('/login')) { const loginUrl = new URL('/login', request.url); loginUrl.searchParams.set('from', pathname); return NextResponse.redirect(loginUrl); } return NextResponse.next(); } // Configure which routes should be processed by the middleware export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) * - public folder */ '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', ], };