| 5 | import { current, versions } from "consts"; |
| 6 | |
| 7 | function getLocale(request: NextRequest): string | undefined { |
| 8 | try { |
| 9 | // Negotiator expects plain object so we need to transform headers |
| 10 | const negotiatorHeaders: Record<string, string> = {}; |
| 11 | request.headers.forEach((value, key) => (negotiatorHeaders[key] = value)); |
| 12 | |
| 13 | // Use negotiator and intl-localematcher to get best locale |
| 14 | const languages = new Negotiator({ |
| 15 | headers: negotiatorHeaders, |
| 16 | }).languages(); |
| 17 | const locales = [...i18n.locales]; |
| 18 | const locale = matchLocale(languages, locales, i18n.defaultLocale); |
| 19 | return ([...i18n.locales] as string[]).includes(locale) |
| 20 | ? locale |
| 21 | : i18n.defaultLocale; |
| 22 | } catch (e) { |
| 23 | console.error(e); |
| 24 | return i18n.defaultLocale; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | export async function middleware(request: NextRequest) { |
| 29 | const { locales, defaultLocale } = i18n; |