UNPKG

nuxt-i18n-micro

Version:

Nuxt I18n Micro is a lightweight, high-performance internationalization module for Nuxt, designed to handle multi-language support with minimal overhead, fast build times, and efficient runtime performance.

35 lines (34 loc) 1.74 kB
import { getEnabledLocaleCodes } from "@i18n-micro/utils/active-locales"; import { withoutAppBaseURL } from "@i18n-micro/utils/app-path"; import { getLocaleCookieName } from "@i18n-micro/utils/cookie"; import { resolveServerLocale } from "@i18n-micro/utils/resolve-locale"; import { getCookie, getQuery, getRequestURL } from "h3"; import { useRuntimeConfig } from "#imports"; export const detectCurrentLocale = (event, config, defaultLocale) => { const { fallbackLocale, defaultLocale: configDefaultLocale, locales, localeCookie, autoDetectLanguage } = config; if (event.context.params?.locale) { return event.context.params.locale.toString(); } const resolvedDefault = defaultLocale || configDefaultLocale || "en"; const validLocales = getEnabledLocaleCodes(locales ?? []); const url = getRequestURL(event); const rawPath = url.pathname.split("?")[0]?.split("#")[0] ?? url.pathname; const cleanPath = withoutAppBaseURL(rawPath, useRuntimeConfig(event).app.baseURL); const pathSegments = cleanPath.split("/").filter(Boolean); const firstSegment = pathSegments[0] ?? ""; const hasLocaleInUrl = Boolean(firstSegment && validLocales.includes(firstSegment)); const queryLocale = getQuery(event)?.locale ? String(getQuery(event).locale) : null; const cookieName = getLocaleCookieName({ localeCookie }); const cookieLocale = cookieName ? getCookie(event, cookieName) : null; const locale = resolveServerLocale({ defaultLocale: resolvedDefault, validLocales, autoDetectLanguage, hasLocaleInUrl, urlLocale: firstSegment || null, queryLocale, cookieLocale, acceptLanguageHeader: event.headers.get("accept-language") }); return locale || fallbackLocale || resolvedDefault; };