|
import 'server-only' |
|
|
|
import { cookies, headers } from 'next/headers' |
|
import Negotiator from 'negotiator' |
|
import { match } from '@formatjs/intl-localematcher' |
|
import type { Locale } from '.' |
|
import { i18n } from '.' |
|
|
|
export const getLocaleOnServer = (): Locale => { |
|
|
|
const locales: string[] = i18n.locales |
|
|
|
let languages: string[] | undefined |
|
|
|
const localeCookie = cookies().get('locale') |
|
languages = localeCookie?.value ? [localeCookie.value] : [] |
|
|
|
if (!languages.length) { |
|
|
|
const negotiatorHeaders: Record<string, string> = {} |
|
headers().forEach((value, key) => (negotiatorHeaders[key] = value)) |
|
|
|
languages = new Negotiator({ headers: negotiatorHeaders }).languages() |
|
} |
|
|
|
|
|
const matchedLocale = match(languages, locales, i18n.defaultLocale) as Locale |
|
return matchedLocale |
|
} |
|
|