Skip to content

Email for professionals and teams

Load locale catalogs on demand

Hieu Nguyen (Jack)07f4ac2f70d5
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index c719803..c8138d8 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -3,7 +3,7 @@ import { cookies } from "next/headers";
import { Geist, Geist_Mono } from "next/font/google";
import { Providers } from "@/components/providers";
import { LanguageProvider } from "@/components/language-provider";
-import { LOCALE_COOKIE, getDirection, resolveLocale } from "@/lib/i18n/utils";
+import { DEFAULT_LOCALE, LOCALE_COOKIE, getDirection, loadMessages, resolveLocale } from "@/lib/i18n/utils";
import { sidebarBootstrapScript } from "@/components/sidebar-state-utils";
import { themeBootstrapScript } from "@/components/theme-utils";
import "./globals.css";
@@ -40,6 +40,7 @@ export const metadata: Metadata = {
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value);
+ const messages = locale === DEFAULT_LOCALE ? undefined : await loadMessages(locale);
return (
<html lang={locale} dir={getDirection(locale)} suppressHydrationWarning>
<head>
@@ -48,7 +49,7 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac
<link rel="icon" href="/api/branding/icon"></link>
</head>
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
- <LanguageProvider initialLocale={locale}><Providers>{children}</Providers></LanguageProvider>
+ <LanguageProvider initialLocale={locale} initialMessages={messages}><Providers>{children}</Providers></LanguageProvider>
</body>
</html>
);
diff --git a/src/components/language-provider.tsx b/src/components/language-provider.tsx
index 65db7b2..7632525 100644
--- a/src/components/language-provider.tsx
+++ b/src/components/language-provider.tsx
@@ -1,8 +1,8 @@
"use client";
-import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
-import { DEFAULT_LOCALE, createTranslator, getDirection, resolveLocale, serializeLocaleCookie } from "@/lib/i18n/utils";
-import type { Locale } from "@/lib/i18n/types";
+import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from "react";
+import { DEFAULT_LOCALE, createTranslator, getDirection, loadMessages, resolveLocale, serializeLocaleCookie } from "@/lib/i18n/utils";
+import type { Locale, Messages } from "@/lib/i18n/types";
import type { LanguageState } from "./language-provider-types";
const LanguageContext = createContext<LanguageState>({
@@ -11,22 +11,37 @@ const LanguageContext = createContext<LanguageState>({
t: createTranslator(DEFAULT_LOCALE),
});
-export function LanguageProvider({ initialLocale, children }: { initialLocale: Locale; children: ReactNode }) {
- const [locale, updateLocale] = useState(initialLocale);
- const value = useMemo<LanguageState>(() => ({ locale, setLocale, t: createTranslator(locale) }), [locale]);
+type Active = { locale: Locale; messages?: Partial<Messages> };
- function setLocale(next: Locale) {
+/**
+ * `initialMessages` is the catalog for `initialLocale`, loaded on the server so the first render is already
+ * translated. English needs none; it is bundled. Other catalogs load on demand when the language changes.
+ */
+export function LanguageProvider({ initialLocale, initialMessages, children }: { initialLocale: Locale; initialMessages?: Partial<Messages>; children: ReactNode }) {
+ const [active, setActive] = useState<Active>({ locale: initialLocale, messages: initialMessages });
+ const latestRequest = useRef(0);
+
+ const setLocale = useCallback((next: Locale) => {
const nextLocale = resolveLocale(next);
- // Preference cookies can be disabled; the selection still works for this session.
- try {
- document.cookie = serializeLocaleCookie(nextLocale, window.location.protocol === "https:");
- } catch {
- // Keep the in-memory preference when cookie storage is unavailable.
- }
- document.documentElement.lang = nextLocale;
- document.documentElement.dir = getDirection(nextLocale);
- updateLocale(nextLocale);
- }
+ const request = ++latestRequest.current;
+ void loadMessages(nextLocale).then((messages) => {
+ if (request !== latestRequest.current) return;
+ // Preference cookies can be disabled; the selection still works for this session.
+ try {
+ document.cookie = serializeLocaleCookie(nextLocale, window.location.protocol === "https:");
+ } catch {
+ // Keep the in-memory preference when cookie storage is unavailable.
+ }
+ document.documentElement.lang = nextLocale;
+ document.documentElement.dir = getDirection(nextLocale);
+ setActive({ locale: nextLocale, messages });
+ }).catch(() => undefined);
+ }, []);
+
+ const value = useMemo<LanguageState>(
+ () => ({ locale: active.locale, setLocale, t: createTranslator(active.locale, active.messages) }),
+ [active, setLocale],
+ );
return (
<LanguageContext.Provider value={value}>
diff --git a/src/lib/i18n/locales.ts b/src/lib/i18n/locales.ts
index c170a8a..b4431f3 100644
--- a/src/lib/i18n/locales.ts
+++ b/src/lib/i18n/locales.ts
@@ -1,13 +1,20 @@
import en from "./en.json";
-import ptBR from "./pt-BR.json";
-import type { Messages } from "./types";
-// Register a catalog and its native display name here (add `dir: "rtl"` for right-to-left scripts). All locale consumers
-// (types, validation, cookies, SSR and the selector) derive from this registry.
+type LocaleEntry = {
+ /** The language's own name, shown in the selector. */
+ label: string;
+ /** Set for right-to-left scripts. */
+ dir?: "rtl";
+ /** English ships in the main bundle as the fallback; every other catalog is fetched when first needed. */
+ load: () => Promise<Record<string, string>>;
+};
+
+// Register a language here with its native name, and add its catalog file next to `en.json`.
+// Types, validation, cookies, SSR and the selector all derive from this registry.
export const locales = {
- en: { label: "English", messages: en },
- "pt-BR": { label: "Português (Brasil)", messages: ptBR },
-} satisfies Record<string, { label: string; messages: Messages; dir?: "rtl" }>;
+ en: { label: "English", load: async () => en },
+ "pt-BR": { label: "Português (Brasil)", load: async () => (await import("./pt-BR.json")).default },
+} satisfies Record<string, LocaleEntry>;
export type Locale = keyof typeof locales;
export const DEFAULT_LOCALE = "en" satisfies Locale;
diff --git a/src/lib/i18n/server.ts b/src/lib/i18n/server.ts
index 8637aef..3d7e591 100644
--- a/src/lib/i18n/server.ts
+++ b/src/lib/i18n/server.ts
@@ -1,7 +1,13 @@
import { cookies } from "next/headers";
-import { LOCALE_COOKIE, createTranslator, resolveLocale } from "./utils";
+import { LOCALE_COOKIE, createTranslator, loadMessages, resolveLocale } from "./utils";
+
+/** The locale chosen in the preference cookie, for server code that must render in it. */
+export async function getRequestLocale() {
+ return resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value);
+}
// For server components and route handlers; client components use `useLanguage()`.
export async function getServerTranslator() {
- return createTranslator(resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value));
+ const locale = await getRequestLocale();
+ return createTranslator(locale, await loadMessages(locale));
}
diff --git a/src/lib/i18n/utils.ts b/src/lib/i18n/utils.ts
index 8cc0781..07cd587 100644
--- a/src/lib/i18n/utils.ts
+++ b/src/lib/i18n/utils.ts
@@ -14,8 +14,9 @@ export function getDirection(locale: Locale): "ltr" | "rtl" {
return (locales[locale] as { dir?: "rtl" }).dir ?? "ltr";
}
-export function getMessages(locale: Locale): Messages {
- return locales[locale].messages;
+/** Fetches the catalog for a locale; English is already bundled, others load on demand. */
+export async function loadMessages(locale: Locale): Promise<Partial<Messages>> {
+ return locales[locale].load();
}
export type TranslationVars = Record<string, string | number | null | undefined>;
@@ -33,8 +34,7 @@ export function translate(messages: Partial<Messages>, key: TranslationKey, vars
// Server-safe translator. A numeric `count` var selects a plural variant: with
// `inbox.unread.one` / `inbox.unread.other` catalog entries, `t("inbox.unread", { count })`
// uses the locale's CLDR category and falls back to the bare key when no variant exists.
-export function createTranslator(locale: Locale): Translator {
- const messages = getMessages(locale);
+export function createTranslator(locale: Locale, messages: Partial<Messages> = en): Translator {
const rules = new Intl.PluralRules(locale);
const known = (key: string) => key in messages || key in en;
return (key, vars) => {
@@ -54,4 +54,4 @@ export function serializeLocaleCookie(locale: Locale, secure: boolean): string {
}
/** Default for pure helpers that take an optional translator, so callers without one (and tests) get English. */
-export const defaultTranslator: Translator = createTranslator(DEFAULT_LOCALE);
+export const defaultTranslator: Translator = createTranslator(DEFAULT_LOCALE, en);
diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjs
index 6285d18..6d0adc9 100644
--- a/tests/i18n.test.mjs
+++ b/tests/i18n.test.mjs
@@ -20,11 +20,13 @@ async function bundleI18n(outfile, extraLocale = false) {
import RootLayout from "./src/app/layout";
import { LanguageProvider, useLanguage } from "./src/components/language-provider";
import { LanguageSelector } from "./src/components/language-selector";
+ import { loadMessages } from "./src/lib/i18n/utils";
export * from "./src/lib/i18n/utils";
export * from "./src/lib/i18n/locales";
function Probe() { return createElement("span", null, useLanguage().t("navigation.inbox")); }
- export function renderLanguage(locale) {
- return renderToStaticMarkup(createElement(LanguageProvider, { initialLocale: locale }, createElement(Probe), createElement(LanguageSelector)));
+ export async function renderLanguage(locale) {
+ const initialMessages = await loadMessages(locale);
+ return renderToStaticMarkup(createElement(LanguageProvider, { initialLocale: locale, initialMessages }, createElement(Probe), createElement(LanguageSelector)));
}
export async function renderLayout(cookieValue) {
globalThis.testLocaleCookie = cookieValue;
@@ -47,7 +49,7 @@ async function bundleI18n(outfile, extraLocale = false) {
setup(builder) {
if (extraLocale) builder.onLoad({ filter: /\/i18n\/locales\.ts$/ }, ({ path }) => ({
contents: readFileSync(path, "utf8").replace("export const locales = {", `export const locales = {
- es: { label: "Español", dir: "rtl", messages: { ...en, "navigation.inbox": "Entrada", "navigation.inbox.one": "{count} entrada", "navigation.inbox.other": "{count} entradas", "language.label": "Idioma" } },`),
+ es: { label: "Español", dir: "rtl", load: async () => ({ ...en, "navigation.inbox": "Entrada", "navigation.inbox.one": "{count} entrada", "navigation.inbox.other": "{count} entradas", "language.label": "Idioma" }) },`),
loader: "ts",
}));
builder.onResolve({ filter: /^(next\/headers|next\/font\/google|@\/components\/providers)$/ }, (args) => ({ path: args.path, namespace: "stub" }));
@@ -74,8 +76,9 @@ const placeholders = (text) => [...new Set([...text.matchAll(/\{(\w+)\}/g)].map(
const pluralBases = new Set(Object.keys(en).filter((key) => key.endsWith(".other")).map(baseOf));
const isPluralKey = (key) => categoryOf(key) && pluralBases.has(baseOf(key));
-test("every registered catalog has the English keys and nonempty messages and label", () => {
- for (const [code, { messages: catalog, label }] of Object.entries(i18n.locales)) {
+test("every registered catalog has the English keys and nonempty messages and label", async () => {
+ for (const [code, { load, label }] of Object.entries(i18n.locales)) {
+ const catalog = await load();
assert.ok(label.trim().length > 0, code);
const plain = (keys) => keys.filter((key) => !isPluralKey(key)).sort();
assert.deepEqual(plain(Object.keys(catalog)), plain(Object.keys(en)), `${code}: keys differ from English`);
@@ -100,8 +103,8 @@ test("missing, invalid and unsupported locale values fall back to English", () =
assert.equal(i18n.resolveLocale("pt-BR"), "pt-BR");
});
-test("translation uses the requested catalog and falls back per key", () => {
- assert.equal(i18n.translate(i18n.getMessages("pt-BR"), "navigation.inbox"), "Caixa de entrada");
+test("translation uses the requested catalog and falls back per key", async () => {
+ assert.equal(i18n.translate(await i18n.loadMessages("pt-BR"), "navigation.inbox"), "Caixa de entrada");
assert.equal(i18n.translate({}, "navigation.inbox"), "Inbox");
});
@@ -111,13 +114,13 @@ test("preference cookie persists for a year, covers every path and is Secure on
assert.equal(i18n.serializeLocaleCookie("bad; Domain=example.com", true), "mailflare-locale=en; Path=/; Max-Age=31536000; SameSite=Lax; Secure");
});
-test("provider server rendering uses initial locale and labels the native language selector", () => {
- const pt = i18n.renderLanguage("pt-BR");
+test("provider server rendering uses initial locale and labels the native language selector", async () => {
+ const pt = await i18n.renderLanguage("pt-BR");
assert.match(pt, /Caixa de entrada/);
assert.match(pt, /<label for="[^"]+"[^>]*>Idioma<\/label>/);
assert.match(pt, /<select id="[^"]+"/);
assert.match(pt, /value="pt-BR" lang="pt-BR" selected=""/);
- assert.match(i18n.renderLanguage("en"), /value="en" lang="en" selected=""/);
+ assert.match(await i18n.renderLanguage("en"), /value="en" lang="en" selected=""/);
});
test("root layout passes the same cookie locale to HTML and provider on first render", async () => {
@@ -137,16 +140,16 @@ test("a locale registered once reaches resolution, translation, cookie, selector
await bundleI18n(extraFile, true);
const extended = await import(pathToFileURL(extraFile).href);
assert.equal(extended.resolveLocale("es"), "es");
- assert.equal(extended.translate(extended.getMessages("es"), "navigation.inbox"), "Entrada");
+ assert.equal(extended.translate(await extended.loadMessages("es"), "navigation.inbox"), "Entrada");
assert.match(extended.serializeLocaleCookie("es", true), /^mailflare-locale=es;/);
- const selector = extended.renderLanguage("es");
+ const selector = await extended.renderLanguage("es");
assert.match(selector, /value="es" lang="es" selected="">Español<\/option>/);
assert.match(selector, />Entrada<\/span>/);
const layout = await extended.renderLayout("es");
assert.match(layout, /<html lang="es"/);
assert.match(layout, />Entrada<\/span>/);
assert.match(layout, /<html lang="es" dir="rtl"/);
- const t = extended.createTranslator("es");
+ const t = extended.createTranslator("es", await extended.loadMessages("es"));
assert.equal(t("navigation.inbox", { count: 1 }), "1 entrada");
assert.equal(t("navigation.inbox", { count: 3 }), "3 entradas");
assert.equal(t("navigation.inbox"), "Entrada");
@@ -155,9 +158,9 @@ test("a locale registered once reaches resolution, translation, cookie, selector
}
});
-test("translations interpolate {vars}, keep unknown placeholders and default to ltr", () => {
+test("translations interpolate {vars}, keep unknown placeholders and default to ltr", async () => {
assert.equal(i18n.translate({ "navigation.inbox": "Hi {name}, {other}" }, "navigation.inbox", { name: "Ana", count: 2 }), "Hi Ana, {other}");
assert.equal(i18n.translate({}, "navigation.inbox", { name: "x" }), "Inbox");
- assert.equal(i18n.createTranslator("pt-BR")("navigation.inbox", { count: 2 }), "Caixa de entrada");
+ assert.equal(i18n.createTranslator("pt-BR", await i18n.loadMessages("pt-BR"))("navigation.inbox", { count: 2 }), "Caixa de entrada");
assert.equal(i18n.getDirection("en"), "ltr");
});