next-i18n-router
Version:
Next.js App Router internationalized routing and locale detection.
55 lines • 2 kB
JavaScript
;
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
const navigation_1 = require("next/navigation");
const getCookie = (name, documentCookie) => {
let cookies = documentCookie;
let cookieArray = cookies.split('; ');
for (let i = 0; i < cookieArray.length; i++) {
let cookiePair = cookieArray[i].split('=');
if (cookiePair[0] === name) {
return cookiePair[1];
}
}
return null;
};
const useCurrentLocale = (i18nConfig, documentCookie) => {
const { basePath = '', locales } = i18nConfig;
if (!documentCookie && typeof window !== 'undefined') {
documentCookie = document.cookie;
}
if (documentCookie) {
const cookieLocale = getCookie(i18nConfig.localeCookie || 'NEXT_LOCALE', documentCookie);
if (cookieLocale && locales.includes(cookieLocale)) {
return cookieLocale;
}
}
if (i18nConfig.noPrefix) {
return i18nConfig.defaultLocale;
}
const currentPathname = (0, navigation_1.usePathname)();
const locale = locales.find(locale => {
// remove trailing slash if present
let base = basePath.replace(/\/$/, '');
// server does not include basePath in usePathname
// https://github.com/vercel/next.js/issues/46562
if (typeof window === 'undefined') {
base = '';
}
return (currentPathname === `${base}/${locale}` ||
// While the return type of usePathname is string, there are times when usePathname returns null, so we need to null check:
// https://nextjs.org/docs/app/api-reference/functions/use-pathname
currentPathname?.startsWith(`${base}/${locale}/`));
});
if (locale) {
return locale;
}
if (!i18nConfig.prefixDefault) {
return i18nConfig.defaultLocale;
}
else {
return undefined;
}
};
exports.default = useCurrentLocale;
//# sourceMappingURL=useCurrentLocale.js.map