41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
|
|
const basePath = '/studio'
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl
|
|
|
|
// Allow all API routes and static files
|
|
// Note: pathname does NOT include basePath when basePath is configured
|
|
if (
|
|
pathname.startsWith('/api/') ||
|
|
pathname.startsWith('/_next') ||
|
|
pathname.startsWith('/favicon') ||
|
|
pathname.includes('.')
|
|
) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
// Allow login page
|
|
if (pathname === '/login') {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
// Check if session cookie exists (simple check, full validation happens in server)
|
|
// Better Auth adds "__Secure-" prefix when served over HTTPS
|
|
const sessionToken = request.cookies.get('better-auth.session_token')
|
|
|| request.cookies.get('__Secure-better-auth.session_token')
|
|
|
|
if (!sessionToken?.value) {
|
|
const loginUrl = new URL(`${basePath}/login`, request.url)
|
|
loginUrl.searchParams.set('callbackUrl', pathname)
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
|
|
return NextResponse.next()
|
|
}
|
|
|
|
export const config = {
|
|
matcher: '/:path*',
|
|
}
|