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- type:
H3Event - An H3 event. see details H3 API docs
- type:
config- type:
object - A locale config that is passed from Nitro.
- Properties:
defaultLocale- type:
Locale - This value is set to the
defaultLocaleoption of Nuxt i18n. If unset, it is set to thelocaleoption loaded from the Vue I18n configuration (i18n.configfile set on thevueI18noption). If neither of these are set, the default value of'en-US'is used.
- type:
fallbackLocale- type:
FallbackLocale - This value is set to the
fallbackLocaleoption loaded from the Vue I18n configuration (i18n.configfile set on thevueI18noption). If no fallback locale has been configured this will default tofalse.
- type:
- type:
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
})