Fix middleware: only run on auth-related routes
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,28 +10,22 @@ const authRoutes = ['/login', '/register']
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl
|
||||
|
||||
// Skip middleware for homepage - let it render statically
|
||||
if (pathname === '/' || pathname === '') {
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
const { supabaseResponse, user } = await updateSession(request)
|
||||
|
||||
// Check if trying to access protected route without auth
|
||||
const isProtectedRoute = protectedRoutes.some(route =>
|
||||
pathname.startsWith(route)
|
||||
pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`)
|
||||
)
|
||||
|
||||
if (isProtectedRoute && !user) {
|
||||
const redirectUrl = new URL('/login/', request.url)
|
||||
// Save the original URL to redirect back after login
|
||||
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.startsWith(route)
|
||||
pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`)
|
||||
)
|
||||
|
||||
if (isAuthRoute && user) {
|
||||
@@ -43,13 +37,14 @@ export async function middleware(request: NextRequest) {
|
||||
|
||||
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 files
|
||||
*/
|
||||
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
|
||||
// Only run middleware on specific routes that need auth handling
|
||||
'/dashboard/:path*',
|
||||
'/settings/:path*',
|
||||
'/subscription/:path*',
|
||||
'/login',
|
||||
'/login/',
|
||||
'/register',
|
||||
'/register/',
|
||||
'/auth/:path*',
|
||||
],
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user