Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

perf(i18n): serve the Lingui catalog as a static chunk, not root loader data (#1659)

Sid310445109ce5
diff --git a/.claude/rules/i18n-lingui-system.md b/.claude/rules/i18n-lingui-system.md
index 1db5d2226e..1f6ba50aaf 100644
--- a/.claude/rules/i18n-lingui-system.md
+++ b/.claude/rules/i18n-lingui-system.md
@@ -39,13 +39,32 @@ runs via `@lingui/vite-plugin` (`lingui()` plugin in `apps/erp/vite.config.ts` a
1. **Mark** strings with macros (see patterns below).
2. **Extract** (`lingui:extract`) scans configured sources → updates `{locale}/{erp,mes}.po`.
-3. **Compile** (`lingui:compile`) → `{locale}/{erp,mes}.mjs` (build artifact, gitignored).
-4. **Load (server)**: `apps/{erp,mes}/app/services/lingui.server.ts` →
- `loadLinguiCatalogForRequest(request, locale)` resolves the language and lazy-imports
- the matching compiled catalog (`erp.mjs` / `mes.mjs`) via `import.meta.glob(..., { import: "messages" })`;
- returns `{}` if not found.
-5. **Provide (client)**: `root.tsx` loader calls the loader, then renders
- `<LocaleProvider locale={appLanguage} catalog={linguiCatalog}>` from `@carbon/locale`.
+3. **Compile**: `@lingui/vite-plugin` (wired in both apps' `vite.config.ts`) compiles a
+ `.po` import into a JS module (`export const messages`) in every Vite environment —
+ SSR and client — so the catalog is a hashed, immutable chunk per locale. The
+ `lingui:compile` → `.mjs` step is no longer read by the apps; it stays only as the
+ turbo build input that invalidates the build cache when a `.po` changes. Catalog
+ paths in `lingui.config.js` use `<rootDir>/…` because the plugin resolves them
+ against the config dir while Vite runs from `apps/<app>` — a bare relative path
+ fails with "not matched to any of your catalogs paths".
+4. **Load**: `apps/{erp,mes}/app/services/lingui.ts` (isomorphic, one per app because
+ the glob names the app's catalog) — `import.meta.glob("…/*/{erp,mes}.po", { import: "messages" })`
+ behind a module-level `Map`. `preloadCatalog(locale)` fills it; `getCatalog(locale)`
+ reads it (`{}` if missing); `useCatalog(locale)` reads and, on a cache miss, preloads
+ then re-renders — that is the live language switch (`/api/locale` → root revalidates
+ with the new cookie → the new chunk is fetched).
+ - Server: the root loader awaits `preloadCatalog(appLanguage)` so SSR is translated,
+ and returns NOTHING about the catalog. It used to return the whole catalog as
+ loader data — ~465 KB raw in every HTML and in every `.data` response, which
+ single-fetch serves uncompressed (`text/x-script`), and the root loader re-ran on
+ every action and search-param change. `root.tsx` now also has a `shouldRevalidate`
+ that skips same-pathname GETs (`isSearchParamOnlyNavigation`); actions still
+ revalidate because root carries the flash `result`.
+ - Client: `entry.client.tsx` awaits `preloadCatalog(document.documentElement.lang)`
+ BEFORE `hydrateRoot` — otherwise a non-`en` page hydrates against an empty catalog
+ and mismatches the server markup. `<html lang>` is the resolved language, set by root.
+5. **Provide**: `root.tsx` renders
+ `<LocaleProvider locale={appLanguage} catalog={useCatalog(appLanguage)}>` from `@carbon/locale`.
`LocaleProvider` (`packages/locale/src/i18n.tsx`) builds a per-render runtime with
`setupI18n()`, `runtime.load(language, catalog)`, `runtime.activate(language)`, and
wraps children in Lingui's `<I18nProvider>`. This is the only active i18n instance.
diff --git a/apps/erp/app/entry.client.tsx b/apps/erp/app/entry.client.tsx
index 9e3770ed89..fc44a38130 100644
--- a/apps/erp/app/entry.client.tsx
+++ b/apps/erp/app/entry.client.tsx
@@ -13,6 +13,7 @@ import { ensureLoggingConfigured } from "@carbon/logger/config.client";
import posthog from "posthog-js";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
+import { preloadCatalog } from "~/services/lingui";
ensureLoggingConfigured();
@@ -43,6 +44,11 @@ if (CONTROLLED_ENVIRONMENT && posthog.__loaded) {
);
}
-startTransition(() => {
- hydrateRoot(document, <HydratedRouter />);
+// The catalog is no longer in loader data, so fetch the active language's
+// chunk before hydrating — otherwise a non-en page hydrates against an empty
+// catalog and mismatches the server markup.
+preloadCatalog(document.documentElement.lang).then(() => {
+ startTransition(() => {
+ hydrateRoot(document, <HydratedRouter />);
+ });
});
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 41a38851ed..eda3a81f01 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -19,7 +19,12 @@ import {
} from "@carbon/react";
import { RootErrorBoundary } from "@carbon/react/ErrorBoundary";
import type { Theme } from "@carbon/utils";
-import { getPreferenceHeaders, modeValidator, themes } from "@carbon/utils";
+import {
+ getPreferenceHeaders,
+ isSearchParamOnlyNavigation,
+ modeValidator,
+ themes
+} from "@carbon/utils";
import { faviconLinks } from "@carbon/utils/favicon";
import { I18nProvider } from "@react-aria/i18n";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -30,7 +35,8 @@ import type {
ActionFunctionArgs,
LinksFunction,
LoaderFunctionArgs,
- MetaFunction
+ MetaFunction,
+ ShouldRevalidateFunction
} from "react-router";
import {
data,
@@ -42,7 +48,7 @@ import {
useLoaderData
} from "react-router";
import SonnerStyle from "sonner/dist/styles.css?url";
-import { loadLinguiCatalogForRequest } from "~/services/lingui.server";
+import { preloadCatalog, useCatalog } from "~/services/lingui";
import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
import NProgress from "~/styles/nprogress.css?url";
@@ -77,6 +83,12 @@ export const meta: MetaFunction = ({ error }) => {
];
};
+// Root data is cookies + env + the flash result. A same-pathname GET (table
+// filter, sort, page, useRevalidator from realtime hooks) can change none of
+// it; actions still revalidate so the flash toast is surfaced.
+export const shouldRevalidate: ShouldRevalidateFunction = (args) =>
+ isSearchParamOnlyNavigation(args) ? false : args.defaultShouldRevalidate;
+
export async function loader({ request, context }: LoaderFunctionArgs) {
const {
AUTH_PROVIDERS,
@@ -106,7 +118,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
const preferences = getPreferenceHeaders(request);
const appLanguage = resolveLanguage(preferences.locale);
- const linguiCatalog = await loadLinguiCatalogForRequest(request, appLanguage);
+ await preloadCatalog(appLanguage);
return data(
{
@@ -135,7 +147,6 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
VERCEL_URL,
XERO_CLIENT_ID
},
- linguiCatalog,
mode: getMode(request),
preferences: getPreferenceHeaders(request),
result: context.get(flashResultContext),
@@ -257,8 +268,8 @@ export default function App() {
const env = loaderData?.env ?? {};
const theme = loaderData?.theme ?? "zinc";
const prefs = loaderData?.preferences;
- const linguiCatalog = loaderData?.linguiCatalog;
const appLanguage = resolveLanguage(prefs.locale);
+ const catalog = useCatalog(appLanguage);
const mode = useMode();
// One client for both consumers: the imperative `window.clientCache`
@@ -288,7 +299,7 @@ export default function App() {
return (
<QueryClientProvider client={queryClient}>
<OperatingSystemContextProvider platform={prefs.platform}>
- <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
+ <LocaleProvider locale={appLanguage} catalog={catalog}>
<I18nProvider locale={prefs.locale}>
<TooltipProvider delayDuration={200}>
<Document mode={mode} theme={theme} lang={appLanguage} env={env}>
diff --git a/apps/erp/app/services/lingui.server.ts b/apps/erp/app/services/lingui.server.ts
deleted file mode 100644
index 99112f2cab..0000000000
--- a/apps/erp/app/services/lingui.server.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { resolveLanguage } from "@carbon/locale";
-import type { Messages } from "@lingui/core";
-
-const catalogLoaders = import.meta.glob(
- "../../../../packages/locale/locales/*/erp.mjs",
- {
- import: "messages"
- }
-) as Record<string, () => Promise<Messages>>;
-
-export async function loadLinguiCatalogForRequest(
- _request: Request,
- locale: string | null | undefined
-) {
- const language = resolveLanguage(locale);
- const catalogPath = `../../../../packages/locale/locales/${language}/erp.mjs`;
- const load = catalogLoaders[catalogPath];
- return load ? load() : {};
-}
diff --git a/apps/erp/app/services/lingui.ts b/apps/erp/app/services/lingui.ts
new file mode 100644
index 0000000000..cd4069bf8b
--- /dev/null
+++ b/apps/erp/app/services/lingui.ts
@@ -0,0 +1,45 @@
+import { resolveLanguage } from "@carbon/locale";
+import { getLogger } from "@carbon/logger";
+import type { Messages } from "@lingui/core";
+import { useEffect, useReducer } from "react";
+
+// The .po is compiled by @lingui/vite-plugin into a hashed chunk per locale,
+// so the client fetches only the active language, cached immutably — instead
+// of the whole catalog riding along in every root loader response.
+const loaders = import.meta.glob(
+ "../../../../packages/locale/locales/*/erp.po",
+ { import: "messages" }
+) as Record<string, () => Promise<Messages>>;
+
+const cache = new Map<string, Messages>();
+const logger = getLogger("erp", "lingui");
+
+export async function preloadCatalog(locale?: string | null) {
+ const language = resolveLanguage(locale);
+ if (cache.has(language)) return;
+ const load =
+ loaders[`../../../../packages/locale/locales/${language}/erp.po`];
+ try {
+ cache.set(language, load ? await load() : {});
+ } catch (err) {
+ // A failed chunk fetch (stale deploy hash, flaky network) must not leave
+ // the SSR page non-interactive: boot with source strings and retry on the
+ // next preload rather than caching the failure.
+ logger.error("Failed to load the catalog", { language, error: err });
+ }
+}
+
+export function getCatalog(locale?: string | null): Messages {
+ return cache.get(resolveLanguage(locale)) ?? {};
+}
+
+// Switching language re-runs the root loader with a new cookie, but the client
+// only preloaded the language it hydrated with — fetch the new one and re-render.
+export function useCatalog(locale?: string | null): Messages {
+ const language = resolveLanguage(locale);
+ const [, rerender] = useReducer((n: number) => n + 1, 0);
+ useEffect(() => {
+ if (!cache.has(language)) preloadCatalog(language).then(rerender);
+ }, [language]);
+ return getCatalog(language);
+}
diff --git a/apps/mes/app/entry.client.tsx b/apps/mes/app/entry.client.tsx
index 172fa074ba..419eda1109 100644
--- a/apps/mes/app/entry.client.tsx
+++ b/apps/mes/app/entry.client.tsx
@@ -13,6 +13,7 @@ import posthog from "posthog-js";
import { startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
+import { preloadCatalog } from "~/services/lingui";
ensureLoggingConfigured();
@@ -49,6 +50,11 @@ if (CONTROLLED_ENVIRONMENT && posthog.__loaded) {
);
}
-startTransition(() => {
- hydrateRoot(document, <HydratedRouter />);
+// The catalog is no longer in loader data, so fetch the active language's
+// chunk before hydrating — otherwise a non-en page hydrates against an empty
+// catalog and mismatches the server markup.
+preloadCatalog(document.documentElement.lang).then(() => {
+ startTransition(() => {
+ hydrateRoot(document, <HydratedRouter />);
+ });
});
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index e0abe04bb7..ad86243b06 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -19,7 +19,12 @@ import {
} from "@carbon/react";
import { RootErrorBoundary } from "@carbon/react/ErrorBoundary";
import type { Theme } from "@carbon/utils";
-import { getPreferenceHeaders, modeValidator, themes } from "@carbon/utils";
+import {
+ getPreferenceHeaders,
+ isSearchParamOnlyNavigation,
+ modeValidator,
+ themes
+} from "@carbon/utils";
import { faviconLinks } from "@carbon/utils/favicon";
import { I18nProvider } from "@react-aria/i18n";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -29,7 +34,8 @@ import { useState } from "react";
import type {
ActionFunctionArgs,
LoaderFunctionArgs,
- MetaFunction
+ MetaFunction,
+ ShouldRevalidateFunction
} from "react-router";
import {
data,
@@ -40,7 +46,7 @@ import {
ScrollRestoration,
useLoaderData
} from "react-router";
-import { loadLinguiCatalogForRequest } from "~/services/lingui.server";
+import { preloadCatalog, useCatalog } from "~/services/lingui";
import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
import NProgress from "~/styles/nprogress.css?url";
@@ -72,6 +78,12 @@ export const meta: MetaFunction = () => {
];
};
+// Root data is cookies + env + the flash result. A same-pathname GET (table
+// filter, sort, page, useRevalidator from realtime hooks) can change none of
+// it; actions still revalidate so the flash toast is surfaced.
+export const shouldRevalidate: ShouldRevalidateFunction = (args) =>
+ isSearchParamOnlyNavigation(args) ? false : args.defaultShouldRevalidate;
+
export async function loader({ request, context }: LoaderFunctionArgs) {
const {
AUTH_PROVIDERS,
@@ -93,7 +105,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
const preferences = getPreferenceHeaders(request);
const appLanguage = resolveLanguage(preferences.locale);
- const linguiCatalog = await loadLinguiCatalogForRequest(request, appLanguage);
+ await preloadCatalog(appLanguage);
return data(
{
@@ -117,7 +129,6 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
mode: getMode(request),
theme: getTheme(request),
preferences,
- linguiCatalog,
result: context.get(flashResultContext)
},
{
@@ -239,8 +250,8 @@ export default function App() {
const env = loaderData?.env ?? {};
const theme = loaderData?.theme ?? "zinc";
const prefs = loaderData?.preferences;
- const linguiCatalog = loaderData?.linguiCatalog;
const appLanguage = resolveLanguage(prefs.locale);
+ const catalog = useCatalog(appLanguage);
/* Dark/Light Mode */
const mode = useMode();
@@ -259,7 +270,7 @@ export default function App() {
return (
<QueryClientProvider client={queryClient}>
<OperatingSystemContextProvider platform={prefs.platform}>
- <LocaleProvider locale={appLanguage} catalog={linguiCatalog}>
+ <LocaleProvider locale={appLanguage} catalog={catalog}>
<I18nProvider locale={prefs.locale}>
<TooltipProvider delayDuration={200}>
<Document mode={mode} theme={theme} lang={appLanguage} env={env}>
diff --git a/apps/mes/app/services/lingui.server.ts b/apps/mes/app/services/lingui.server.ts
deleted file mode 100644
index dae2a52d1a..0000000000
--- a/apps/mes/app/services/lingui.server.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { resolveLanguage } from "@carbon/locale";
-import type { Messages } from "@lingui/core";
-
-const catalogLoaders = import.meta.glob(
- "../../../../packages/locale/locales/*/mes.mjs",
- {
- import: "messages"
- }
-) as Record<string, () => Promise<Messages>>;
-
-export async function loadLinguiCatalogForRequest(
- _request: Request,
- locale: string | null | undefined
-) {
- const language = resolveLanguage(locale);
- const catalogPath = `../../../../packages/locale/locales/${language}/mes.mjs`;
- const load = catalogLoaders[catalogPath];
- return load ? load() : {};
-}
diff --git a/apps/mes/app/services/lingui.ts b/apps/mes/app/services/lingui.ts
new file mode 100644
index 0000000000..a5ed3a7844
--- /dev/null
+++ b/apps/mes/app/services/lingui.ts
@@ -0,0 +1,45 @@
+import { resolveLanguage } from "@carbon/locale";
+import { getLogger } from "@carbon/logger";
+import type { Messages } from "@lingui/core";
+import { useEffect, useReducer } from "react";
+
+// The .po is compiled by @lingui/vite-plugin into a hashed chunk per locale,
+// so the client fetches only the active language, cached immutably — instead
+// of the whole catalog riding along in every root loader response.
+const loaders = import.meta.glob(
+ "../../../../packages/locale/locales/*/mes.po",
+ { import: "messages" }
+) as Record<string, () => Promise<Messages>>;
+
+const cache = new Map<string, Messages>();
+const logger = getLogger("mes", "lingui");
+
+export async function preloadCatalog(locale?: string | null) {
+ const language = resolveLanguage(locale);
+ if (cache.has(language)) return;
+ const load =
+ loaders[`../../../../packages/locale/locales/${language}/mes.po`];
+ try {
+ cache.set(language, load ? await load() : {});
+ } catch (err) {
+ // A failed chunk fetch (stale deploy hash, flaky network) must not leave
+ // the SSR page non-interactive: boot with source strings and retry on the
+ // next preload rather than caching the failure.
+ logger.error("Failed to load the catalog", { language, error: err });
+ }
+}
+
+export function getCatalog(locale?: string | null): Messages {
+ return cache.get(resolveLanguage(locale)) ?? {};
+}
+
+// Switching language re-runs the root loader with a new cookie, but the client
+// only preloaded the language it hydrated with — fetch the new one and re-render.
+export function useCatalog(locale?: string | null): Messages {
+ const language = resolveLanguage(locale);
+ const [, rerender] = useReducer((n: number) => n + 1, 0);
+ useEffect(() => {
+ if (!cache.has(language)) preloadCatalog(language).then(rerender);
+ }, [language]);
+ return getCatalog(language);
+}
diff --git a/lingui.config.js b/lingui.config.js
index 4ed79b401b..158849babe 100644
--- a/lingui.config.js
+++ b/lingui.config.js
@@ -13,7 +13,7 @@ export default defineConfig({
format: "po",
catalogs: [
{
- path: "packages/locale/locales/{locale}/erp",
+ path: "<rootDir>/packages/locale/locales/{locale}/erp",
include: [
"apps/erp/app",
"packages/react/src",
@@ -26,7 +26,7 @@ export default defineConfig({
exclude: ["**/*.server.*", "**/*.test.*", "**/*.spec.*"]
},
{
- path: "packages/locale/locales/{locale}/mes",
+ path: "<rootDir>/packages/locale/locales/{locale}/mes",
include: [
"apps/mes/app",
"packages/react/src",
diff --git a/packages/locale/AGENTS.md b/packages/locale/AGENTS.md
index 73ec9e5f05..a872efdc80 100644
--- a/packages/locale/AGENTS.md
+++ b/packages/locale/AGENTS.md
@@ -46,4 +46,4 @@ import { LocaleProvider, supportedLanguages, resolveLanguage, defaultLanguage,
- `.claude/rules/i18n-lingui-system.md` — full i18n system docs, marking patterns, gotchas
- `lingui.config.js` (root) — catalog config, source paths, locale list
- `@carbon/glossary` — terms use `msg` descriptors for i18n
-- `apps/{erp,mes}/app/services/lingui.server.ts` — server-side catalog loading
+- `apps/{erp,mes}/app/services/lingui.ts` — isomorphic catalog loading (`preloadCatalog` / `getCatalog` / `useCatalog`)
diff --git a/packages/locale/src/i18n.tsx b/packages/locale/src/i18n.tsx
index 6c39e5a7dd..d3737fb4cb 100644
--- a/packages/locale/src/i18n.tsx
+++ b/packages/locale/src/i18n.tsx
@@ -1,11 +1,11 @@
-import { setupI18n } from "@lingui/core";
+import { type Messages, setupI18n } from "@lingui/core";
import { I18nProvider as LinguiProvider } from "@lingui/react";
import { type ReactNode, useMemo } from "react";
import { resolveLanguage } from "./config";
type LocaleProviderProps = {
locale?: string | null;
- catalog?: Record<string, string>;
+ catalog?: Messages;
children: ReactNode;
};