Why We Made ODAC.JS Translations Synchronous

November 18, 2026
10 min read
49 reads
Why We Made ODAC.JS Translations Synchronous

Most Node.js internationalization setups force you into a bad trade-off: either you pay an async tax on every string lookup in your controllers, or you ship a bloated 40 KB JSON catalog to the browser just to translate three buttons.

In ODAC.JS v1.6.0 and v1.7.0, we tore down that compromise and rebuilt our entire localization stack from end to end. Translations are now synchronous in memory, disambiguated by context, automatically tree-shaken for browser scripts, and enforced in CI before a single untranslated string reaches production.

Here is why we made those architectural calls and how the full-stack i18n pipeline works across templates, controllers, browser code, and HTTP caches.

Show Me The Code

Before we unpack the design decisions, look at what full-stack localization looks like in ODAC.JS today. No third-party packages, no custom /api/i18n fetch endpoints, and no manual <html lang> wiring.

Start with a controller in controller/Order.js, an HTML view in view/content/order.html, and a browser script in view/js/cart.js:

// controller/Order.js
module.exports = function (Odac) {
  const orderId = Odac.Request.get('id')
  const title = Odac.__x('Gül', 'verb')
  const notice = Odac.__('Order #%s1 shipped', orderId)

  Odac.set({ title, notice, orderId })
  Odac.View.skeleton('main').set('content', 'order')
}
<!-- view/content/order.html -->
<h1><odac var="title" /></h1>
<p><odac translate>Order #<odac var="orderId" /> is on the way</odac></p>
<button type="button">
  <odac translate context="button">Open</odac>
</button>
// view/js/cart.js
Odac.action({
  load() {
    document.querySelector('#status').textContent = __('%s1 items selected', selected.length)
    document.querySelector('#action').textContent = __x('Open', 'button')
  }
})

Then keep every file under storage/language/ synchronized and verified from your terminal:

# Extract keys from views and JS/TS sources across all language files
npx odac lang:sync

# Fail CI on missing, unused, dynamic, or untranslated keys
npx odac lang:check --strict

# Preview or delete unused keys across every catalog
npx odac lang:prune --write

Every layer speaks the same key format, shares the same JSON files in storage/language/, and keeps your runtime free of disk I/O.

Killing the Async Tax in Node.js Controllers

Previously, Odac.__() returned a Promise and parsed translations per request. On paper, making file-backed helpers asynchronous sounds polite to the Node.js event loop, until you write real application logic.

Every controller message, validation summary, and notification had to be awaited, turning simple string formatting into noisy async chains. Worse, reading or parsing locale data on the hot path wastes CPU cycles for content that barely changes between deploys.

ODAC.JS now preloads every file in storage/language/ into memory when your application boots. That makes Odac.__(), Odac.__x(), Odac.Lang.get(), and Odac.Lang.getx() completely synchronous, returning a string directly with zero disk waits on the request path.

What if you want to update copy without restarting your server? You still get live updates:

  • Background revalidation: Every worker checks storage/language/ on disk in the background every 2 seconds.
  • Zero request blocking: The request that notices an updated file is served the previous in-memory catalog immediately while the new version loads in the background.
  • Fault-tolerant JSON parsing: If someone saves malformed JSON mid-edit, ODAC.JS logs a warning once per broken file version and keeps serving the last valid catalog until the syntax error is fixed.
  • Atomic safety for external tools: Admin panels or scripts writing to storage/language/*.json should write to a temporary file and rename it atomically so no worker reads a half-written file.

In development (debug mode), missing keys are automatically collected and written in sorted key order to every language file at once: the default language receives the key itself, and every other language receives "" so diffs stay clean and predictable. In production, disk writes stay off unless you explicitly set "collect": true under lang in odac.json.

ODAC.JS in-memory translation store loading language JSON files with 2-second background revalidation and synchronous Odac.__() and Odac.__x() lookups

Context Disambiguation Without Ugly Key Hacks

If you have ever localized a real product, you have hit the homonym wall. In Turkish, "Gül" means both "Rose" (the flower) and "Smile" (the verb). In English, "Open" can be a button action on a modal or the status of a support ticket.

Most frameworks push teams into inventing brittle key conventions like "Open_button" or "Gül (verb)". The moment a translator forgets the suffix or a fallback occurs, users see internal naming hacks leaked straight onto the page.

ODAC.JS treats context as a first-class part of a translation key's identity. In templates, attach a context attribute to <odac translate>; in controllers and browser code, call Odac.__x() or __x():

<odac translate context="flower">Gül</odac>
<odac translate context="verb">Gül</odac>
// Context comes second, followed by any placeholder arguments
const heading = Odac.__x('Gül', 'verb')
const bouquet = Odac.__x('%s1 gül', 'flower', 3)

Inside storage/language/en.json, plain keys remain simple strings, while contextual keys store a nested map of context to translation (with "" representing the context-free default):

{
  "Gül": {
    "": "Gül",
    "flower": "Rose",
    "verb": "Smile"
  }
}

If a context translation is missing in the active language, ODAC.JS falls back to that exact context in lang.default, and then to the key itself. It will never silently grab a different context's translation, so a button label never accidentally renders as a ticket status.

Zero-Bloat Browser Translations in view/js/

Frontend localization usually fails in one of two ways. Either you bundle the entire language catalog into client JavaScript, shipping admin panel copy and internal error messages to anonymous visitors, or you add a client-side fetch() waterfall before interactive widgets can render text.

ODAC.JS eliminates both problems by statically scanning your view/js/ scripts for __() and __x() calls (or Odac.__() and Odac.__x(), if another third-party library already claims global __). Only the keys actually referenced in view/js/ are embedded into the HTML response inside a <script type="application/json" id="odac-lang"> block, already translated into the active language.

If your frontend scripts do not call __() or __x(), nothing is injected into the document at all. When the user navigates via ODAC.JS AJAX navigation, the browser sends X-Odac-Lang with its active language and content version, so the server sends updated frontend translations only when the language changes or a language file was edited on disk.

ODAC.JS static subset extraction from view/js/ scripts into inline #odac-lang JSON and X-Odac-Lang AJAX delta headers

Two rules matter most when writing browser translations:

  • Use textContent, never innerHTML: Both __() and __x() return plain text, and placeholder values often come from user input. Assigning to innerHTML turns translated strings into an XSS vector.
  • Pass literal keys only: Static extraction reads source code directly, so computed template strings cannot be shipped to the browser. Map dynamic values to literal calls instead.
// view/js/orders.js

// Safe: plain text assignment with literal keys
const statusLabels = {
  shipped: __('Shipped'),
  pending: __('Pending')
}
statusEl.textContent = statusLabels[order.status]

// Safe: user-supplied placeholder assigned via textContent
greetingEl.textContent = __('Hello %s1', user.name)

// Unsafe: never assign translated strings containing user input to innerHTML
// greetingEl.innerHTML = __('Hello %s1', user.name)

Need to format dates or numbers in the browser? Call Odac.lang() to retrieve the active two-letter language code and pass it straight to Intl.DateTimeFormat.

Document Semantics, RTL, and Cache-Safe Routing

Localization breaks in subtle ways when the HTTP response and the <html> element disagree. A Turkish page still marked <html lang="en"> breaks screen readers, triggers unwanted browser translation bars, and even ruins CSS text-transform: uppercase rules (where i must become İ in Turkish).

When your application declares languages (either multiple files in storage/language/, or lang.default / lang.supported in odac.json), ODAC.JS manages document metadata automatically:

  • Automatic <html lang dir>: Every rendered page replaces <html lang> and sets dir via Odac.Lang.dir() ('rtl' for Arabic, Hebrew, Persian, Urdu, and related scripts; 'ltr' otherwise), and AJAX navigation updates both attributes when the language changes.
  • Strict language whitelisting: Setting lang.supported in odac.json locks down which locales can ever be served. Arbitrary Accept-Language headers never create rogue language files on disk and fall back cleanly to lang.default.
  • Automatic Content-Language and Vary: Responses include Content-Language, and header-negotiated pages automatically emit Vary: Accept-Language so proxies never serve one visitor's language to another.

That caching detail is critical for performance. When a page's language comes from Accept-Language, the ODAC.JS Proxy refuses to cache it even if you call Odac.cache(), because the same URL produces different HTML per visitor.

For public, SEO-indexed, cacheable pages, put the language in the URL and call Odac.Lang.set() explicitly:

// route/www.js
Odac.Route.page('/{lang}/about', 'About')

// controller/About.js
module.exports = function (Odac) {
  Odac.Lang.set(Odac.request('lang'))
  Odac.cache(3600)
  Odac.View.skeleton('main').set('content', 'about')
}

Because each language now owns a dedicated URL (/en/about, /tr/about), ODAC.JS omits Vary: Accept-Language and lets Odac.cache() serve cached HTML at full speed while keeping hreflang indexing clean. Reserve shared header-negotiated URLs for authenticated pages like dashboards and account settings.

Automating Catalog Hygiene in CI

Manual translation JSON maintenance always collapses at scale. Someone deletes a key from en.json and forgets tr.json, an empty string slips into a release, or dead keys linger for years because nobody dares delete them.

ODAC.JS ships three CLI commands designed to make catalog drift impossible:

  • npx odac lang:sync: Scans compiled .html views and skeletons (so <odac translate>Hello <odac var="name" /></odac> resolves accurately to "Hello %s1") alongside JavaScript and TypeScript files (Odac.__(), Odac.__x(), Odac.Lang.get(), Odac.Lang.getx(), __() and __x()). Missing keys are added cleanly across every file in storage/language/.
  • npx odac lang:check --strict: Built for CI pipelines. Exits with code 1 if any language file is out of sync, contains unused keys, references dynamic non-literal keys, or still has untranslated "" entries.
  • npx odac lang:prune: Lists unused keys in a safe dry run first. Passing --write removes them across every language file simultaneously, refusing to run if any file contains invalid JSON.

What about legitimate dynamic keys like Odac.__(`status.${order.status}`)? You have two layers of protection. First, declare expected patterns in lang.keep inside odac.json:

{
  "lang": {
    "default": "en",
    "supported": ["en", "tr", "ar"],
    "keep": ["status.*"],
    "highlightMissing": true
  }
}

Second, whenever key collection is active in development, ODAC.JS records runtime-observed keys with their last-used date in storage/.cache/lang-runtime.json. Even when you run npx odac lang:prune --write, keys seen at runtime are protected and listed separately unless you explicitly pass --include-runtime. Because CI has no local runtime cache, npx odac lang:check --strict will still remind you to register those patterns in lang.keep or refactor them into literal key maps.

Terminal output showing npx odac lang:prune protecting runtime-observed keys and npx odac lang:check --strict passing in CI

Migration Notes and Gotchas

If you are upgrading an existing application to ODAC.JS v1.6.0 or v1.7.0, keep these edge cases in mind:

  • Chaining .then() on Odac.__() breaks: Because Odac.__() now returns a string synchronously instead of a Promise, calling Odac.__(...).then(...) throws a TypeError. Existing code using await Odac.__(...) continues to work, though you can safely drop await across controllers.
  • Single-language non-English sites: If your site uses only one language and it is not English, set "lang": { "default": "tr" } in odac.json so ODAC.JS writes <html lang="tr"> automatically instead of leaving the skeleton untouched.
  • Visual debugging for missing copy: Enable "highlightMissing": true under lang in odac.json during development to wrap fallback strings in ⟦text⟧ right in the browser, making untranslated UI impossible to miss during QA.
  • Do not hand-delete keys from one file: Removing a key from a single JSON file without running npx odac lang:prune --write will simply restore it on the next sync because the remaining language files still hold it.

Localization should never feel like duct-taping a second application onto your Node.js stack. By moving catalogs into memory, extracting only the browser keys you actually call, wiring document direction and proxy cache rules automatically, and validating every key in CI, ODAC.JS makes multi-language shipping as fast and predictable as the rest of your codebase.