import { type NextRequest, NextResponse } from 'next/server' import { updateSession } from '@/lib/supabase/middleware' // Routes that require authentication const protectedRoutes = ['/dashboard', '/settings', '/subscription'] // Routes that should redirect to dashboard if already authenticated const authRoutes = ['/login', '/register'] export async function middleware(request: NextRequest) { const { pathname } = request.nextUrl const { supabaseResponse, user } = await updateSession(request) // Check if trying to access protected route without auth const isProtectedRoute = protectedRoutes.some(route => pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`) ) if (isProtectedRoute && !user) { const redirectUrl = new URL('/login/', request.url) redirectUrl.searchParams.set('redirectTo', pathname) return NextResponse.redirect(redirectUrl) } // Check if trying to access auth routes while already authenticated const isAuthRoute = authRoutes.some(route => pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`) ) if (isAuthRoute && user) { return NextResponse.redirect(new URL('/dashboard/', request.url)) } return supabaseResponse } export const config = { matcher: [ // Only run middleware on specific routes that need auth handling '/dashboard/:path*', '/settings/:path*', '/subscription/:path*', '/login', '/login/', '/register', '/register/', '/auth/:path*', ], }