- Add server-side authentication check for /[locale]/dashboard routes - Create Supabase client in middleware to verify user session - Redirect unauthenticated users to /[locale]/login with locale preservation - Chain to existing i18n middleware for all other routes - Authentication check runs before i18n middleware processing Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
import createIntlMiddleware from 'next-intl/middleware';
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { locales, defaultLocale } from './i18n/config';
|
|
import { createClient } from '@/lib/supabase/middleware';
|
|
|
|
const intlMiddleware = createIntlMiddleware({
|
|
locales,
|
|
defaultLocale,
|
|
localePrefix: 'always',
|
|
});
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
// Create a response object to pass to Supabase client
|
|
let response = NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
});
|
|
|
|
// Check if accessing dashboard route
|
|
const pathname = request.nextUrl.pathname;
|
|
const isDashboardRoute = pathname.match(/^\/(de|en|sr)\/dashboard/);
|
|
|
|
if (isDashboardRoute) {
|
|
// Create Supabase client
|
|
const supabase = createClient(request, response);
|
|
|
|
// Check authentication
|
|
const { data: { user } } = await supabase.auth.getUser();
|
|
|
|
if (!user) {
|
|
// Extract locale from path
|
|
const locale = pathname.split('/')[1];
|
|
// Redirect to login page with locale preserved
|
|
return NextResponse.redirect(new URL(`/${locale}/login`, request.url));
|
|
}
|
|
}
|
|
|
|
// Continue with i18n middleware for all routes
|
|
return intlMiddleware(request);
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
'/',
|
|
'/(de|en|sr)/:path*',
|
|
'/((?!api|_next|_vercel|.*\\..*).*)',
|
|
],
|
|
};
|