Composables

defineI18nLocaleDetector

The defineI18nLocaleDetector() is composable used to define a function which detects the locale on the server-side, it's called per request on the server.

The defineI18nLocaleDetector() is composable used to define a function which detects the locale on the server-side, it's called per request on the server.

The function needs to return a locale string.

You can use @intlify/h3 utilities in the locale detector function, these are auto imported.

This composable is experimental. You need to configure filepath to experimental.localeDetector option.

Type

type LocaleConfig = {
  defaultLocale: Locale
  fallbackLocale: FallbackLocale
}
declare function defineI18nLocaleDetector(
  detector: (event: H3Event, config: LocaleConfig) => string
): (event: H3Event, config: LocaleConfig) => string

Parameters

detector

A function that is the locale detector, that has the following parameters:

  • event
  • config
    • type: object
    • A locale config that is passed from Nitro.
    • Properties:
      • defaultLocale
        • type: Locale
        • This value is set to the defaultLocale option of Nuxt i18n. If unset, it is set to the locale option loaded from the Vue I18n configuration (i18n.config file set on the vueI18n option). If neither of these are set, the default value of 'en-US' is used.
      • fallbackLocale
        • type: FallbackLocale
        • This value is set to the fallbackLocale option loaded from the Vue I18n configuration (i18n.config file set on the vueI18n option). If no fallback locale has been configured this will default to false.

Usage

An example of a locale detector:

// Detect based on query, cookie, header
export default defineI18nLocaleDetector((event, config) => {
  const query = tryQueryLocale(event, { lang: '' })
  if (query) {
    return query.toString()
  }

  const cookie = tryCookieLocale(event, { lang: '', name: 'i18n_locale' })
  if (cookie) {
    return cookie.toString()
  }

  const header = tryHeaderLocale(event, { lang: '' })
  if (header) {
    return header.toString()
  }

  return config.defaultLocale
})

Copyright © 2024