import.meta.glob('./locales/*/**/*.json', { eager: true }) is one of the fastest ways to wire up internationalization in an Astro + Vite project. It is also one of the easiest ways to ship over a megabyte of unused JSON to every browser that loads a single hydrated React island.

The trap is subtle because Astro defaults to zero client JavaScript. Static .astro pages read translations on the server and emit plain HTML, so everything looks lightweight early on. The moment you hydrate a client island that imports your getTranslations() helper—whether it is a navigation bar, a calculator, or a comment form—Vite follows the static import graph into your dictionary store and bundles every JSON file matched by that eager glob into the client chunk.

In a multi-page web app with roughly 200 interactive routes across two locales (en and zh), a single monolithic tools.json file quickly accumulates three completely different kinds of text:

  1. Navigation catalog copy (name and desc for every route) — needed by shared chrome, search, and category lists.
  2. Search metadata and FAQs (seoTitle, seoDesc, and long-form FAQ arrays) — only ever read during server rendering or static site generation.
  3. Route-specific interactive UI labels (form inputs, validation messages, presets, unit selectors) — only needed by the one island mounted on the current URL.

In our English locale alone, those three buckets totaled ~710 KB: 45.7 KB for catalog names and descriptions, 342.9 KB for SEO titles, descriptions, and FAQs, and 322.0 KB across 197 per-route UI dictionaries (an average of ~1.6 KB per page). Shipping all of it to every visitor meant 93% of the English translation payload—and 100% of the second locale's payload—was dead weight on any given route.

Splitting Dictionaries Along Lifecycle Boundaries

Instead of fighting Vite's bundler with brittle manual chunk rules, the cleanest fix is to align your directory layout with where each piece of text is actually consumed:

  • src/i18n/locales/{lang}/features/tools.json (Shared client + server, 45.7 KB in en): Strictly { name, desc } per route slug. This stays inside the eager import.meta.glob because shared navigation islands genuinely need it.
  • src/i18n/seo/{lang}/tools-seo.json (Server-only, 342.9 KB in en): Lives outside locales/, read only by a .server.ts module during Astro SSG/SSR. Zero bytes reach the client bundle.
  • src/i18n/tool-ui/{lang}/{slug}.json (Per-route, ~1.6 KB average): Also lives outside locales/. On each route, the Astro page loads only the active slug's JSON, registers it on the server for SSR, and injects a tiny inline bootstrap script so the hydrated island sees the exact same keys on the client.

In the Astro route ([slug].astro), the handoff takes four lines:

const toolUiData = getToolUiMessages(lang, slug); const toolNamespace = `Tools.${slug}`; registerMessages(lang, toolNamespace, toolUiData); const toolUiBootstrapScript = serializeMessagesBootstrap(lang, toolNamespace, toolUiData); 

The page then renders <script is:inline set:html={toolUiBootstrapScript} /> before the island mounts.

Four Edge Cases You Hit with Runtime Namespace Injection

Once you move from static-only dictionaries to per-route runtime registration, four sneaky bugs show up immediately if you are not careful.

1. Inline <script> Breakout (XSS)

JSON.stringify() is not safe to drop directly into an inline <script> tag. If any translated string contains </script>, the HTML parser closes the script block early and executes whatever follows. Escaping < to its Unicode sequence makes the payload safe for inline HTML without changing the parsed JavaScript object:

export function serializeMessagesBootstrap( locale: Locale, namespacePath: string, data: Record<string, unknown>, ): string { const payload = JSON.stringify({ locale, namespacePath, data }).replace(/</g, '\\u003c'); return `window.__I18N_MESSAGES__=${payload};`; } 

2. Prototype Pollution and Sibling-Key Clobbering

Because registerMessages() accepts a dot-delimited namespacePath like Tools.barista-fire-calculator, two invariants must hold at the boundary:

  • Reject prototype segments: Before walking the object tree, parseNamespacePath() trims the input, splits on ., and rejects empty segments or any occurrence of __proto__, constructor, or prototype. Likewise, resolvePath() checks Object.hasOwn(cursor, part) on every hop so inherited Object.prototype keys like toString can never masquerade as valid translations.
  • Shallow-merge leaf nodes: The shared catalog already populated dictionaries.en.Tools['cr-calculator'] with { name, desc }. Overwriting that leaf with uiData would erase the route's title and description. Merging { ...existingLeaf, ...data } preserves catalog keys alongside the injected UI keys.
const FORBIDDEN_NAMESPACE_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype']); function parseNamespacePath(raw: string): string[] | null { const normalized = raw.trim(); if (!normalized) return null; const segments = normalized.split('.'); if (segments.some((seg) => seg.length === 0 || FORBIDDEN_NAMESPACE_SEGMENTS.has(seg))) { return null; } return segments; } 

3. Stale Memoized Translator Caches

In React islands, getTranslations(locale, namespace) is typically memoized in a module-level Map<string, TranslateFunction> so that components receive a referentially stable t function and do not re-trigger useEffect or useMemo hooks on every render.

That cache creates a subtle race when registerMessages() runs after a translator was already requested. Suppose the navigation bar calls getTranslations('en', 'Tools') first, caching a closure that holds a reference to dictionaries.en.Tools. Then the route registers Tools.barista-fire-calculator—replacing the leaf object with a new shallow-merged copy. Any cached translator for an ancestor (en:, en:Tools), the exact node (en:Tools.barista-fire-calculator), or a descendant (en:Tools.barista-fire-calculator.ui) could now point to a stale object reference.

To prevent stale reads without flushing unrelated namespaces, store.ts exposes an invalidation listener that translator.ts subscribes to:

onDictionaryInvalidate((locale, segments) => { const normalizedPath = segments.join('.'); const prefix = `${locale}:`; const ancestorKeys = new Set<string>([prefix]); for (let i = 1; i <= segments.length; i++) { ancestorKeys.add(`${prefix}${segments.slice(0, i).join('.')}`); } const descendantPrefix = `${prefix}${normalizedPath}.`; for (const cacheKey of translationCache.keys()) { if (ancestorKeys.has(cacheKey) || cacheKey.startsWith(descendantPrefix)) { translationCache.delete(cacheKey); } } }); 

4. Boundary-Validated, Idempotent Hydration Sync

On the client, syncMessagesFromWindow() runs both at module evaluation time and at the top of getTranslations(). Tracking lastSyncedRaw by reference makes repeat calls an O(1) pointer comparison, while parseWindowMessagesPayload() validates that window.__I18N_MESSAGES__ is a plain object with a registered Locale, a safe namespacePath, and a plain-object data record before merging it into the store. If a page injects a corrupted bootstrap payload, it fails fast with an explicit error instead of silently rendering missing keys.

Locking the Split with Vitest Contract Tests

Directory conventions rot quickly under daily feature work. One contributor adds seoTitle back into locales/en/features/tools.json, and the bundle bloat returns silently. We enforce the three-tier boundary in CI with a Vitest contract suite (toolI18n.contract.test.ts):

it('keeps locales/{en,zh}/features/tools.json strictly limited to { name, desc }', () => { const registrySlugs = TOOLS_REGISTRY.map((t) => t.slug); expect(Object.keys(enMeta).sort()).toEqual([...registrySlugs].sort()); for (const slug of registrySlugs) { const keys = Object.keys(enMeta[slug]).sort(); expect(keys).toEqual(['desc', 'name']); } }); 

The same suite asserts three more invariants across every registered route and locale:

  1. No seoTitle, seoDesc, or faqs key leaks into any tool-ui/{lang}/{slug}.json file.
  2. Every FAQ item in seo/{lang}/tools-seo.json has non-empty question and answer strings.
  3. Both SSR registerMessages() and client window.__I18N_MESSAGES__ synchronization resolve nested UI keys (such as ui.spendingLabel) while preserving sibling name and desc fields from the catalog.

Summary

Separating translation files by execution boundary—shared catalog, server-only metadata, and per-route inline payloads—eliminated over 660 KB of dead English JSON (and its Chinese counterpart) from client island chunks without adding runtime fetches or client-side loading spinners. Combined with ancestor/descendant cache invalidation, < script escaping, and a Vitest contract test that forbids schema drift, the split stays fast as the route count grows. This architecture runs in production across the Astro + React island pages on Lifevor.