- Use request.nextUrl.clone() instead of new URL() for redirects - This preserves the /leopost basePath in redirect URLs - Fixes 404 error when unauthenticated user visits /dashboard Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
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) {
|
|
// Use nextUrl.clone() to preserve basePath in redirect
|
|
const redirectUrl = request.nextUrl.clone()
|
|
redirectUrl.pathname = '/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 === route || pathname === `${route}/` || pathname.startsWith(`${route}/`)
|
|
)
|
|
|
|
if (isAuthRoute && user) {
|
|
// Use nextUrl.clone() to preserve basePath in redirect
|
|
const url = request.nextUrl.clone()
|
|
url.pathname = '/dashboard/'
|
|
return NextResponse.redirect(url)
|
|
}
|
|
|
|
return supabaseResponse
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
// Only run middleware on specific routes that need auth handling
|
|
// Note: /auth/callback is excluded - it handles its own auth flow
|
|
'/dashboard/:path*',
|
|
'/settings/:path*',
|
|
'/subscription/:path*',
|
|
'/login',
|
|
'/login/',
|
|
'/register',
|
|
'/register/',
|
|
],
|
|
}
|