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.
24 lines (23 loc) • 1.04 kB
JavaScript
import { getQuery, getCookie, getRequestURL } from "h3";
export const detectCurrentLocale = (event, config, defaultLocale) => {
const { fallbackLocale, defaultLocale: configDefaultLocale, locales } = config;
if (event.context.params?.locale) {
return event.context.params.locale.toString();
}
const queryLocale = getQuery(event)?.locale;
if (queryLocale) {
return queryLocale.toString();
}
if (locales && locales.length > 0) {
const url = getRequestURL(event);
const querySplit = url.pathname.split("?");
const cleanPath = querySplit[0]?.split("#")[0];
if (!cleanPath) return defaultLocale || "en";
const pathSegments = cleanPath.split("/").filter(Boolean);
const firstSegment = pathSegments[0] || "";
if (firstSegment && locales.some((l) => l.code === firstSegment)) {
return firstSegment;
}
}
return (getCookie(event, "user-locale") || event.headers.get("accept-language")?.split(",")[0] || fallbackLocale || defaultLocale || configDefaultLocale || "en").toString();
};