50 lines
1.5 KiB
TypeScript
50 lines
1.5 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 { supabaseResponse, user } = await updateSession(request)
|
|
const { pathname } = request.nextUrl
|
|
|
|
// Check if trying to access protected route without auth
|
|
const isProtectedRoute = protectedRoutes.some(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)
|
|
)
|
|
|
|
if (isAuthRoute && user) {
|
|
return NextResponse.redirect(new URL('/dashboard', request.url))
|
|
}
|
|
|
|
return supabaseResponse
|
|
}
|
|
|
|
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)$).*)',
|
|
],
|
|
}
|