Add src/middleware.ts

This commit is contained in:
2026-06-10 20:57:32 +00:00
parent 685a4c9be9
commit ff7b22eaa9

38
src/middleware.ts Normal file
View File

@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from 'next/server';
import { i18n } from './lib/i18nConfig';
const PUBLIC_FILE_REGEX = /\.(.*)$/;
export function middleware(request: NextRequest) {
const locale = request.cookies.get('NEXT_LOCALE')?.value || i18n.defaultLocale;
const { pathname } = request.nextUrl;
// Skip internal Next.js paths and static files
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
PUBLIC_FILE_REGEX.test(pathname)
) {
return;
}
// Check if there is any supported locale in the pathname
const pathnameHasLocale = i18n.locales.some(
(loc) => pathname.startsWith(`/${loc}/`) || pathname === `/${loc}`
);
if (pathnameHasLocale) {
return NextResponse.next();
}
// Rewrite to include the default locale if no locale is present
request.nextUrl.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(request.nextUrl);
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/',
],
};