fix(i18n): remove conflicting middleware.ts in favor of proxy.ts
This commit is contained in:
@@ -1,74 +0,0 @@
|
|||||||
import { NextResponse } from 'next/server'
|
|
||||||
import type { NextRequest } from 'next/server'
|
|
||||||
import { i18n } from './i18n.config'
|
|
||||||
|
|
||||||
function getLocale(request: NextRequest): string {
|
|
||||||
const acceptLanguage = request.headers.get('accept-language')
|
|
||||||
const defaultLocale = i18n.defaultLocale
|
|
||||||
const supportedLocales = i18n.locales.map((l) => l.code)
|
|
||||||
|
|
||||||
if (!acceptLanguage) {
|
|
||||||
return defaultLocale
|
|
||||||
}
|
|
||||||
|
|
||||||
// Very basic parser for Accept-Language header
|
|
||||||
// Example header: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
|
|
||||||
const languages = acceptLanguage
|
|
||||||
.split(',')
|
|
||||||
.map((lang) => {
|
|
||||||
const [code, qValue] = lang.split(';q=')
|
|
||||||
const quality = qValue ? parseFloat(qValue) : 1.0
|
|
||||||
return { code: code.trim().split('-')[0].toLowerCase(), quality } // Extract primary subtag (e.g., 'en-US' -> 'en')
|
|
||||||
})
|
|
||||||
.sort((a, b) => b.quality - a.quality)
|
|
||||||
|
|
||||||
// Find the first matching supported locale
|
|
||||||
for (const { code } of languages) {
|
|
||||||
if (supportedLocales.includes(code as any)) {
|
|
||||||
return code
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaultLocale
|
|
||||||
}
|
|
||||||
|
|
||||||
export function middleware(request: NextRequest) {
|
|
||||||
const { pathname } = request.nextUrl
|
|
||||||
const locales = i18n.locales.map((l) => l.code)
|
|
||||||
|
|
||||||
// Bypass paths that should not be localized
|
|
||||||
const bypassPaths = [
|
|
||||||
'/api',
|
|
||||||
'/_next',
|
|
||||||
'/admin',
|
|
||||||
'/favicon.ico',
|
|
||||||
'/robots.txt',
|
|
||||||
'/sitemap.xml',
|
|
||||||
'/site.webmanifest',
|
|
||||||
'/icon', // standard icons
|
|
||||||
]
|
|
||||||
|
|
||||||
if (bypassPaths.some((path) => pathname.startsWith(path))) {
|
|
||||||
return NextResponse.next()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if there is any supported locale in the pathname
|
|
||||||
const pathnameHasLocale = locales.some(
|
|
||||||
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
|
|
||||||
)
|
|
||||||
|
|
||||||
if (pathnameHasLocale) {
|
|
||||||
return NextResponse.next()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect if there is no locale
|
|
||||||
const locale = getLocale(request)
|
|
||||||
request.nextUrl.pathname = `/${locale}${pathname}`
|
|
||||||
|
|
||||||
return NextResponse.redirect(request.nextUrl)
|
|
||||||
}
|
|
||||||
|
|
||||||
export const config = {
|
|
||||||
// Matcher ignoring `/_next/` and `/api/`
|
|
||||||
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user