Unverified Commit 5b5ea47c authored by Milo's avatar Milo Committed by GitHub

Avoiding try-catch block on examples/app-dir-i18n-routing (#51786)

`Negotiator.languages()` accepts an array of available locales and
returns only results that are present in it.

This effectively eliminates the need to use a try-catch block when
calling `matchLocale`.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 702d3d29
...@@ -11,15 +11,17 @@ function getLocale(request: NextRequest): string | undefined { ...@@ -11,15 +11,17 @@ function getLocale(request: NextRequest): string | undefined {
const negotiatorHeaders: Record<string, string> = {} const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value)) request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
// Use negotiator and intl-localematcher to get best locale
let languages = new Negotiator({ headers: negotiatorHeaders }).languages()
// @ts-ignore locales are readonly // @ts-ignore locales are readonly
const locales: string[] = i18n.locales const locales: string[] = i18n.locales
try {
return matchLocale(languages, locales, i18n.defaultLocale) // Use negotiator and intl-localematcher to get best locale
} catch (_e) { let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
return i18n.defaultLocale locales
} )
const locale = matchLocale(languages, locales, i18n.defaultLocale)
return locale
} }
export function middleware(request: NextRequest) { export function middleware(request: NextRequest) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment