import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password']; const authOnlyRoutes = ['/login', '/register']; // routes that should NOT be accessed when logged in export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; const token = request.cookies.get('accessToken')?.value; const isAuthenticated = !!token; // If a logged-in user opens home, send them to dashboard. if (isAuthenticated && pathname === '/') { return NextResponse.redirect(new URL('/today', request.url)); } // Always allow public routes first if (publicRoutes.includes(pathname)) { // If user is already logged in and tries to access login/register → redirect to dashboard if (isAuthenticated && authOnlyRoutes.includes(pathname)) { return NextResponse.redirect(new URL('/today', request.url)); } return NextResponse.next(); } // Protected routes: redirect to login if no token if (!isAuthenticated) { // Prevent loop: if somehow redirecting to login from login, just continue if (pathname === '/login') { return NextResponse.next(); } const loginUrl = new URL('/login', request.url); loginUrl.searchParams.set('from', pathname); return NextResponse.redirect(loginUrl); } return NextResponse.next(); } export const config = { matcher: [ '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', ], };