Files
gh-hopeoverture-worldbuildi…/skills/supabase-auth-ssr-setup/assets/middleware.ts
2025-11-29 18:46:51 +08:00

29 lines
942 B
TypeScript

import { type NextRequest } from 'next/server';
import { updateSession } from '@/lib/supabase/middleware';
export async function middleware(request: NextRequest) {
const { supabaseResponse, user } = await updateSession(request);
// If accessing protected route without authentication, redirect to login
if (!user && request.nextUrl.pathname.startsWith('/dashboard')) {
const redirectUrl = new URL('/login', request.url);
redirectUrl.searchParams.set('redirect', request.nextUrl.pathname);
return Response.redirect(redirectUrl);
}
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
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};