server.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import 'server-only'
  2. import { cookies, headers } from 'next/headers'
  3. import Negotiator from 'negotiator'
  4. import { match } from '@formatjs/intl-localematcher'
  5. import type { Locale } from '.'
  6. import { i18n } from '.'
  7. export const getLocaleOnServer = (): Locale => {
  8. // @ts-expect-error locales are readonly
  9. const locales: string[] = i18n.locales
  10. let languages: string[] | undefined
  11. // get locale from cookie
  12. const localeCookie = cookies().get('locale')
  13. languages = localeCookie?.value ? [localeCookie.value] : []
  14. if (!languages.length) {
  15. // Negotiator expects plain object so we need to transform headers
  16. const negotiatorHeaders: Record<string, string> = {}
  17. headers().forEach((value, key) => (negotiatorHeaders[key] = value))
  18. // Use negotiator and intl-localematcher to get best locale
  19. languages = new Negotiator({ headers: negotiatorHeaders }).languages()
  20. }
  21. // match locale
  22. const matchedLocale = match(languages, locales, i18n.defaultLocale) as Locale
  23. return matchedLocale
  24. }
  25. // We enumerate all dictionaries here for better linting and typescript support
  26. // We also get the default import for cleaner types
  27. const dictionaries = {
  28. 'en': () => import('@/dictionaries/en.json').then(module => module.default),
  29. 'zh-Hans': () => import('@/dictionaries/zh-Hans.json').then(module => module.default),
  30. } as { [locale: string]: () => Promise<any> }
  31. export const getDictionary = async (locale: Locale = 'en') => {
  32. try {
  33. return await dictionaries[locale]()
  34. }
  35. catch (e) { console.error('locale not found', locale) }
  36. }