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) {
|
export async function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl
|
const { pathname } = request.nextUrl
|
||||||
|
|
||||||
// Skip middleware for homepage - let it render statically
|
|
||||||
if (pathname === '/' || pathname === '') {
|
|
||||||
return NextResponse.next()
|
|
||||||
}
|
|
||||||
|
|
||||||
const { supabaseResponse, user } = await updateSession(request)
|
const { supabaseResponse, user } = await updateSession(request)
|
||||||
|
|
||||||
// Check if trying to access protected route without auth
|
// Check if trying to access protected route without auth
|
||||||
const isProtectedRoute = protectedRoutes.some(route =>
|
const isProtectedRoute = protectedRoutes.some(route =>
|
||||||
pathname.startsWith(route)
|
pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`)
|
||||||
)
|
)
|
||||||
|
|
||||||
if (isProtectedRoute && !user) {
|
if (isProtectedRoute && !user) {
|
||||||
const redirectUrl = new URL('/login/', request.url)
|
const redirectUrl = new URL('/login/', request.url)
|
||||||
// Save the original URL to redirect back after login
|
|
||||||
redirectUrl.searchParams.set('redirectTo', pathname)
|
redirectUrl.searchParams.set('redirectTo', pathname)
|
||||||
return NextResponse.redirect(redirectUrl)
|
return NextResponse.redirect(redirectUrl)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if trying to access auth routes while already authenticated
|
// Check if trying to access auth routes while already authenticated
|
||||||
const isAuthRoute = authRoutes.some(route =>
|
const isAuthRoute = authRoutes.some(route =>
|
||||||
pathname.startsWith(route)
|
pathname === route || pathname === `${route}/` || pathname.startsWith(`${route}/`)
|
||||||
)
|
)
|
||||||
|
|
||||||
if (isAuthRoute && user) {
|
if (isAuthRoute && user) {
|
||||||
@@ -43,13 +37,14 @@ export async function middleware(request: NextRequest) {
|
|||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: [
|
matcher: [
|
||||||
/*
|
// Only run middleware on specific routes that need auth handling
|
||||||
* Match all request paths except for the ones starting with:
|
'/dashboard/:path*',
|
||||||
* - _next/static (static files)
|
'/settings/:path*',
|
||||||
* - _next/image (image optimization files)
|
'/subscription/:path*',
|
||||||
* - favicon.ico (favicon file)
|
'/login',
|
||||||
* - public folder files
|
'/login/',
|
||||||
*/
|
'/register',
|
||||||
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
|
'/register/',
|
||||||
|
'/auth/:path*',
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user