Translation runtime
The translation runtime turns source content into localized application content. It combines the active locale, published catalogs, runtime translation requests, cache state, and message formatting so project code can use one translation path. The core runtime also serves direct project requests and long-running file translation jobs. This page focuses on that path; see Localization runtime and shared domain, Localization configuration, and Message formatting for the wider domain and its configuration rules.
Resolution model
Translation request path
The runtime resolves a message against the active locale before it contacts a service. It first uses the source message for the default locale, then checks the locale cache for a stored translation. If the cache has no entry, the runtime can request a translation, store the result, and format the returned content for the caller.
The main path is:
flowchart TD
A[Project code] --> B[Read active locale and i18n state]
B --> C[Normalize lookup locale and message identity]
C --> D{Default locale?}
D -->|Yes| E[Use source message]
D -->|No| F[Read locale catalog cache]
F --> G{Translation found?}
G -->|Yes| H[Format translated content]
G -->|No| I[Request runtime translation]
I --> J[Store resolved content]
J --> H
E --> K[Return localized value]
H --> K
The same model serves string content, JSX content, and dictionary values. A caller can choose a plain lookup, a source fallback, or a runtime fallback. The final formatting step uses the message format and variables supplied by the lookup.
References: packages/…/I18nCache.ts• L457-489 packages/…/I18nCache.ts• L685-702 packages/…/helpers.ts• L70-137 packages/…/interpolateMessage.ts• L18-41
Translation functions
The public translation functions provide different timing and fallback choices over the same cache. gt performs a fast lookup after its asynchronous setup. t provides a synchronous source-or-catalog path. tx waits for a missing string translation and then returns the formatted result.
| Function | Main purpose | Missing catalog entry |
|---|---|---|
gt | Resolve messages registered or prepared for runtime use | Returns the source while development hot reload may request the entry in the background |
t | Resolve a string or tagged template in the current locale | Returns the source after a synchronous lookup |
tx | Ask for a runtime translation of string content | Waits for the cache miss request and then returns the source if no translation resolves |
| JSX runtime path | Resolve translated JSX content | Requests a runtime translation and falls back to the source JSX |
Lookup options carry the message format, locale override, stable identity, translator context, character limit, review need, and interpolation variables. The runtime uses the identity and metadata for lookup and sends the relevant metadata with a runtime request. It keeps interpolation separate from lookup so a translated message can be rendered with values from the current call.
References: packages/…/getGT.ts• L22-26 packages/…/getGT.ts• L83-117 packages/…/t.ts• L15-60 packages/…/tx.ts• L31-80 packages/…/options.ts• L12-49
Cache and request state
Locale caches
I18nCache is the shared coordinator for translation and dictionary data. It owns one cache per locale and can load each cache from startup data, a remote catalog, or an application loader. The default locale has source content available immediately, while target locales can load on demand.
Each translation cache uses a stable message hash built from source content and lookup metadata. A cache miss creates one in-flight request for that identity. Several callers that miss at the same time share that request rather than send duplicate work. Misses are also grouped into bounded batches so the runtime can use the translation service without treating every message as a separate request.
Catalog entries can expire according to the configured cache lifetime. A load in progress is shared by callers for the same locale. Applications can also update translation or dictionary snapshots when a server or development tool streams newer content into the runtime.
References: packages/…/I18nCache.ts• L105-187 packages/…/I18nCache.ts• L457-475 packages/…/ResourceCache.ts• L9-69 packages/…/TranslationsCache.ts• L105-199 packages/…/dedupePending.ts• L5-20
Dictionary resolution
A dictionary is a named tree of source entries. The default-locale dictionary defines the source shape. A target dictionary can contain only some leaves, so a request for a missing entry or subtree can combine existing target content with runtime translations for the missing source leaves.
This gives project code a complete dictionary view without requiring every target value to be present before the request. The runtime caches each materialized entry or subtree and shares concurrent materialization work. A requested dictionary path still needs a matching source entry; the runtime treats a missing source path as a real error rather than inventing content.
References: packages/…/I18nCache.ts• L298-405 packages/…/DictionaryCache.ts• L42-133 packages/…/materialize-dictionary.ts• L20-82
Condition store
The condition store supplies the locale, region, and enabled state that translation functions use without passing these values through every call. It resolves the locale against the configured supported set when the store is created or changed. The shared singleton is installed during runtime setup.
Server applications use an asynchronous condition store so each request keeps its own locale while concurrent requests run together. withGT creates that request scope. In React applications, the provider-facing condition store supplies read-only runtime context to hooks and components. When internationalization is disabled, translation functions use the configured default locale instead of a target locale.
References: packages/…/ReadonlyConditionStore.ts• L5-35 packages/…/WritableConditionStore.ts• L11-25 packages/…/singleton-operations.ts• L5-15 packages/…/AsyncConditionStore.ts• L27-78 packages/…/withGT.ts• L3-8
Service boundaries
Catalog loading
Catalog loading supplies translations that already exist outside the runtime. The cache selects one of four modes: the General Translation remote store, a custom remote store, an application loader, or no loader. This choice is independent of runtime translation, so an application can load catalogs without allowing new translation requests.
The remote catalog is scoped by project and locale. Optional version and branch values select a known catalog view. Locale aliases are converted to canonical service values before the catalog is read.
| Catalog mode | Source of target translations | Runtime effect |
|---|---|---|
| General Translation remote | The configured project store | Loads published translations by locale |
| Custom remote | A configured remote URL | Loads application-hosted translations |
| Custom loader | An application function | Lets the project control loading and storage |
| Disabled | No external catalog | Lookup starts empty and can still use runtime translation if enabled |
References: packages/…/getLoadTranslationsType.ts• L5-39 packages/…/routeCreateTranslationLoader.ts• L16-69 packages/…/createRemoteTranslationLoader.ts• L29-45 packages/…/I18nCache.ts• L140-177
Runtime translation service
Runtime translation is the service path for content that the catalog cannot resolve. GTRuntime holds locale rules and request defaults. It validates configured locale identities, resolves aliases to service locale codes, and passes project credentials or a user-token provider to the shared request path.
The shared runtime path accepts one entry or a batch. It normalizes shorthand options, requires a target locale and project access, and uses the configured source locale or the library default. It groups entries by stable content hash, sends source and target locales with shared metadata, and returns results in the same shape as the input. Successful results are narrowed to the requested content format before they reach callers.
The request boundary uses the General Translation API by default and accepts a custom API URL. It disables SDK retries so the runtime-owned fetch timeout remains the controlling limit. Raw failed responses are read for a structured error field or plain text, with Unknown error as the final fallback when the body cannot be read. Failed SDK results with response data are converted through ApiError.fromResponse; results without response data rethrow their underlying error. This keeps status and useful upstream detail available to project-facing callers.
The project-facing adapter supplies the configured access and locale rules to these direct calls. It exposes both single-entry and multi-entry translation requests while preserving the shared result contract.
References: packages/…/runtime.ts• L86-124 packages/…/runtime.ts• L143-224 packages/…/runtime.ts• L228-260 packages/…/runtime.ts• L282-351 packages/…/runtimeTranslate.ts• L59-124 packages/…/runtimeTranslate.ts• L130-185 packages/…/runtimeTranslate.ts• L267-406 packages/…/validateResponse.ts• L4-25 packages/…/unwrapApiResult.ts• L16-34 packages/…/createGtApi.ts• L96-168
Project translation jobs
The project-facing service also supports asynchronous file translation. enqueueFiles validates file inputs and model providers, maps configured locales to service locale values, batches the files, and returns job data. awaitJobs polls those jobs until they finish or its polling limit ends, then returns normalized status data so project code does not manage the polling loop itself.
These jobs use the same project and locale configuration as direct runtime requests but have a different completion model. Direct requests return translation results in one call. File jobs return identifiers and status data that later calls resolve. The adapter keeps service locale values on the wire and maps configured locale aliases back into project-facing results.
References: packages/…/index.ts• L282-334 packages/…/enqueueFiles.ts• L1-7 packages/…/awaitJobs.ts• L3-20 packages/…/createGtApi.ts• L100-116 packages/…/createGtApi.ts• L307-389 packages/…/enqueueFiles.ts• L42-57
Node project service
The Node service prepares the shared runtime for server code. initializeGT installs the locale configuration, cache, and asynchronous condition store. Request entry points then call withGT so all translation work in that request reads the correct locale.
This boundary keeps request state separate from shared catalog and service configuration. It also gives server code one setup point for credentials, project data, catalog loading, and runtime translation behavior.
References: packages/…/initializeGT.ts• L11-25 packages/…/withGT.ts• L3-8 packages/…/AsyncConditionStore.ts• L37-51
React project service
The React service adapts the shared cache to component rendering. ReactI18nCache uses the common cache model, while I18nStore provides snapshots, updates, subscriptions, and background runtime translation for hooks. When a translation or dictionary becomes available, the store emits a matching event so tracked lookups can render the new value.
React dictionary hooks use the default dictionary as the source of truth. They use a target entry when one exists and otherwise resolve the source entry through the shared translation path. Runtime failures are handled as background work, so the component keeps the untranslated content instead of receiving an unhandled promise rejection.
References: packages/…/initializeGTSRA.ts• L1-17 packages/…/ReactI18nCache.ts• L1-6 packages/…/I18nStore.ts• L44-111 packages/…/I18nStore.ts• L181-228 packages/…/useTranslations.ts• L21-119
Errors and logging
Resolution errors
The cache places lookup errors behind a common boundary. In development, most cache and service errors are thrown so a project can fix them early. In production, the runtime logs the error and returns the caller's fallback. Missing dictionary source paths remain hard errors because a safe fallback cannot be built without source content.
The core service reports distinct failures for missing API access, missing project identity, missing source or target locale, invalid locales, failed API responses, and timeouts. An API key or a user-token provider can supply access. API failures preserve the status, status text, and best available response detail: a structured error field, response text, or Unknown error when the body cannot be read. SDK failures with response metadata become ApiError values, while failures without response metadata keep their original error. The project-facing adapter also rejects unsupported model providers before it starts a file translation job.
References: packages/…/I18nCache.ts• L584-625 packages/…/I18nCache.ts• L627-683 packages/…/I18nCache.ts• L713-747 packages/…/runtimeTranslate.ts• L59-124 packages/…/validateResponse.ts• L4-25 packages/…/unwrapApiResult.ts• L16-34 packages/…/errors.ts• L5-77 packages/…/diagnostics.ts• L45-94 packages/…/createGtApi.ts• L326-346
Runtime diagnostics
The i18n layer uses warning and error output for missing loaders, invalid service setup, and handled cache failures. Its log level can be read from the _GENERALTRANSLATION_LOG_LEVEL environment setting. The core service also provides structured log levels, context, metadata, and custom handlers for applications that need richer diagnostics.
React background translation failures are logged once per distinct error and are capped to prevent a repeated service failure from filling the log. The user-facing guard remains source content, so logging does not change the normal rendering contract.
References: packages/…/logger.ts• L1-19 packages/…/logLevel.ts• L1-27 packages/…/logger.ts• L6-27 packages/…/I18nStore.ts• L113-142
Change checklist
When these files or sections are changed, remember to consider these:
- When lookup identity or metadata changes, keep message registration, catalog keys, runtime request metadata, and cache updates aligned.
- When cache loading changes, check both catalog loading and runtime translation selection. They are separate service decisions.
- When condition-store behavior changes, check Node request scope, React provider state, disabled-i18n behavior, and all functions that read the active locale.
- When dictionary materialization changes, preserve the source-tree contract and the merge between existing target leaves and missing source leaves.
- When runtime request preparation changes, keep auth checks, source and target locale defaults, custom locale mapping, and service locale normalization in the same order.
- When runtime result handling changes, preserve input shape, entry order for arrays, stable hashes, and format-specific success validation.
- When API error handling changes, preserve the distinction between raw response parsing, SDK results with response metadata, and errors without response data. Keep status and the best available body detail in the resulting diagnostic.
- When project job contracts change, keep enqueue result job IDs aligned with
awaitJobsinput and preserve the distinction between direct results and polled status. - When the project-facing adapter changes, preserve canonical service locales on outbound requests and configured locale aliases on returned project data.
- When file job validation or batching changes, keep model-provider checks, job ID collection, status normalization, and polling behavior aligned.
- When runtime errors change, keep development throw behavior, production fallback behavior, React background logging, and hard dictionary-source errors distinct.
- When service credentials, locale mapping, or the translation SDK boundary changes, check both remote catalog paths and runtime translation request targets. Preserve timeout ownership and error detail.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Translation code runs before runtime initialization | The condition store, configuration, or cache cannot provide locale data | Initialize the project runtime before calling translation functions |
A request runs outside the Node withGT scope | Development calls fail without request locale context; production uses a warned fallback | Wrap each request entry point in withGT |
| A target locale is invalid or outside the supported set | Lookup fails or resolves to the default locale instead of the requested target | Use valid locale codes and configure supported locales or mappings |
| A direct runtime request has neither an API key nor a user-token provider | Authentication fails before the translation request is sent | Configure one supported access method |
| A direct runtime request has no project ID or target locale | The request fails before the service can resolve content | Set project identity and a target locale in the call or runtime defaults |
| A target catalog has no loader and runtime translation is disabled | The cache has no target entry and returns source content | Configure a catalog loader or enable a runtime translation API |
| Runtime translation lacks project access or credentials | A cache miss cannot reach the translation service | Provide the required project and access settings |
| A runtime request uses an unstable hash or loses entry order | Cache entries can collide or callers can receive the wrong result for an ordered batch | Preserve the hash inputs and map record responses back through the original request order |
| A runtime API returns a JSON body without the expected error field, a non-JSON body, or an unreadable body | The caller can lose the upstream error detail or receive only a generic error | Keep structured-field parsing, text fallback, and Unknown error fallback at the response boundary |
| A runtime API returns content in the wrong format or omits a requested result | The caller receives a controlled translation error instead of usable localized content | Keep response validation and missing-result handling at the API boundary |
| A project-facing request sends an unsupported model provider | File translation enqueueing fails before a job starts | Use one of the supported model providers |
| A locale alias is sent without service normalization or returned without alias restoration | The service can reject the locale or project data can use inconsistent locale keys | Keep outbound canonicalization and inbound alias mapping at the adapter boundary |
| A dictionary target is requested without a matching source path | The runtime cannot materialize a safe value | Keep target dictionary paths aligned with the default dictionary |
| A runtime request fails in a React background update | The component keeps source content and the failure is logged | Inspect the diagnostic error and restore service access or catalog data |
| A file job is polled with an incomplete job list or expires before completion | The project receives incomplete status data and may stop before translations finish | Pass all returned job IDs to awaitJobs and set a suitable polling timeout |
Key files
| File | Why to read it |
|---|---|
| packages/…/helpers.ts | Shows the shared lookup, fallback, and formatting boundaries for string and JSX content. |
| packages/…/I18nCache.ts | Coordinates locale caches, catalog loads, dictionary materialization, runtime misses, and error handling. |
| packages/…/TranslationsCache.ts | Shows message identity, pending-request sharing, batching, and cache updates for one locale. |
| packages/…/DictionaryCache.ts | Shows how partial target dictionaries become complete values from source content. |
| packages/…/ReadonlyConditionStore.ts | Defines the locale and i18n state that translation functions consume. |
| packages/…/AsyncConditionStore.ts | Shows how server requests keep locale state isolated. |
| packages/…/initializeGT.ts | Shows the Node setup boundary that installs the shared services. |
| packages/…/runtime.ts | Defines the project-facing runtime for locale rules, request defaults, and translation service access. |
| packages/…/runtimeTranslate.ts | Defines shared request preparation, batching, locale normalization, result validation, timeout ownership, and API error handling. |
| packages/…/createGtApi.ts | Connects project-facing translation and file-job services to shared credentials, locale mapping, batching, and API error handling. |
| packages/…/validateResponse.ts | Defines how failed raw API responses retain structured or plain-text error detail. |
| packages/…/unwrapApiResult.ts | Defines how SDK results become data or project-facing API errors. |
| packages/…/enqueueFiles.ts | Defines the options for starting asynchronous file translation jobs. |
| packages/…/awaitJobs.ts | Defines the polling options and status result for asynchronous translation jobs. |
| packages/…/errors.ts | Defines the core runtime diagnostics for access, locale, API, and timeout failures. |
| packages/…/I18nStore.ts | Shows React snapshots, subscriptions, cache updates, and background translation behavior. |
| packages/…/useTranslations.ts | Shows how project components consume source and target dictionary content. |