Add src/middleware.ts

This commit is contained in:
2026-06-11 02:43:40 +00:00
parent d4a87d985c
commit c8e7d4d53a

44
src/middleware.ts Normal file
View File

@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { i18n } from './i18n';
const { locales, defaultLocale } = i18n;
function getLocaleFromHeaders(request: NextRequest): string {
const acceptLanguageHeader = request.headers.get('accept-language');
if (acceptLanguageHeader) {
const languages = acceptLanguageHeader.split(',').map(l => l.split(';')[0].trim());
for (const lang of languages) {
if (locales.includes(lang)) {
return lang;
}
}
}
return defaultLocale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Check if the pathname already contains a locale
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) {
return;
}
// Redirect if no locale
const locale = getLocaleFromHeaders(request);
request.nextUrl.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(request.nextUrl);
}
export const config = {
matcher: [
// Skip all internal paths like /_next/ (static assets, api routes, etc.)
// Also skip favicon.ico
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};