AbsoluteJS

Internationalization

AbsoluteJS resolves each request's locale, formats ICU messages with the platform's Intl, and type-checks message keys and parameters against your default catalog. React and Svelte pages translate on the server and hydrate with the same messages.

#Message Catalogs

Write the default locale's catalog as a TypeScript module and wrap it in defineMessages(). It returns the object unchanged, typed with its literal strings, which is what lets t() check keys and parameters. Top-level keys are namespaces.

TS
// src/i18n/messages/en.ts
import { defineMessages } from '@absolutejs/absolute/i18n';

export default defineMessages({
  cart: {
    count:
      '{count, plural, =0 {Your cart is empty} one {# item} other {# items}}'
  },
  common: {
    greeting: 'Hello, {name}!',
    updated: 'Updated {when, date, medium}'
  }
});

Type every other locale as Translation<typeof en>: the same tree with string leaves. A missing key is a type error.

TS
// src/i18n/messages/fr.ts
import type { Translation } from '@absolutejs/absolute/i18n';
import type en from './en';

export default {
  cart: {
    count:
      '{count, plural, =0 {Votre panier est vide} one {# article} other {# articles}}'
  },
  common: {
    greeting: 'Bonjour, {name} !',
    updated: 'Mis à jour le {when, date, medium}'
  }
} satisfies Translation<typeof en>;

Messages use ICU syntax: arguments, plural (with =N, offset: and #), selectordinal, select, number, and date/time styles, nested. Plurals follow the locale's own rules.

#defineI18n

defineI18n() from @absolutejs/absolute takes your locales, the default catalog as messages, and a loader for each other locale. Other catalogs load on first use and are cached. Each is merged over the default catalog, so a gap falls back to the default language.

TS
// src/i18n/index.ts
import { defineI18n } from '@absolutejs/absolute';
import en from './messages/en';

export const i18n = defineI18n({
  defaultLocale: 'en',
  loaders: {
    ar: () => import('./messages/ar'),
    fr: () => import('./messages/fr')
  },
  locales: ['en', 'fr', 'ar'],
  messages: en
});

loaders must cover every locale except the default one; a missing loader is a type error. The remaining options control how a request's locale is chosen:

TS
defineI18n({
  defaultLocale: 'en',
  loaders: { fr: () => import('./messages/fr') },
  locales: ['en', 'fr'],
  messages: en,

  // 'prefix' (default) | 'domain' | 'negotiate'
  strategy: 'prefix',
  // prefix only: serve the default locale under /en too
  prefixDefault: false,
  // prefix + prefixDefault: 307 unprefixed page navigations to a locale
  redirect: false,
  // domain only: locale → host
  domains: { en: 'example.com', fr: 'example.fr' },
  // Cookie that remembers a visitor's choice (default 'locale')
  cookieName: 'locale',
  // Route param that carries the locale (default 'locale')
  localeParam: 'locale',
  // Origin for absolute hreflang URLs (default: the request's origin)
  baseUrl: 'https://example.com'
});
strategyWhere the locale comes from
prefix (default)The first path segment: /fr/about. Unprefixed paths are the default locale. With prefixDefault, unprefixed paths negotiate instead.
domainThe request host, mapped through domains. An unknown host negotiates.
negotiateOne URL for every locale: the locale cookie, then Accept-Language, then the default.

#i18nPlugin

Pass the instance to i18nPlugin() and use it on your server. Under the prefix strategy, register localized routes with an optional :locale param.

TS
// src/backend/server.ts
import { asset, i18nPlugin, prepare } from '@absolutejs/absolute';
import { handleReactPageRequest } from '@absolutejs/absolute/react';
import { Elysia } from 'elysia';
import { i18n } from '../i18n';
import { About } from '../frontend/react/pages/About';

const { absolutejs, manifest } = await prepare();

export const server = new Elysia()
  .use(absolutejs)
  .use(i18nPlugin(i18n))
  // Serves /about, /fr/about and /ar/about. /de/about is a 404.
  .get('/:locale?/about', ({ i18n: requestI18n }) =>
    handleReactPageRequest({
      Page: About,
      index: asset(manifest, 'AboutIndex'),
      props: {
        alternates: requestI18n.alternates(),
        i18n: requestI18n.payload(['common', 'cart'])
      }
    })
  )
  .get('/:locale?/hello', ({ i18n: requestI18n, locale }) => ({
    greeting: requestI18n.t('common.greeting', { name: 'Ada' }),
    locale,
    // '/fr/about'
    path: requestI18n.localizePath('/about', 'fr')
  }));
ContextEvery handler gets locale and an i18n object: t(), the format helpers, payload(), alternates() and localizePath().
payload()i18n.payload(namespaces) returns this locale’s messages for hydration. List namespaces so a page ships only what it uses, and pass the result as a page prop.
HeadersEvery response gets Content-Language. When the locale came from the cookie or Accept-Language, it also gets Vary: Accept-Language, Cookie.
Unknown localesA :locale param that is not a configured locale gets a 404.
getRequestLocale()getRequestLocale() returns the current request’s locale and text direction, for code that has no access to the handler context.

#React

Wrap the page in I18nProvider with the payload prop, and call useI18n() below it. Both come from @absolutejs/absolute/react/hooks. Pass your default catalog's type to the hook to check keys and parameters. The page sets lang and dir on <html> itself.

TSX
// src/frontend/react/pages/About.tsx
import type { AlternateLink, I18nPayload } from '@absolutejs/absolute/i18n';
import { Head } from '@absolutejs/absolute/react/components';
import { I18nProvider, useI18n } from '@absolutejs/absolute/react/hooks';
import type en from '../../../i18n/messages/en';

type AboutProps = {
  alternates: AlternateLink[];
  i18n: I18nPayload;
};

const Greeting = () => {
  const { formatNumber, t } = useI18n<typeof en>();

  return (
    <main>
      <h1>{t('common.greeting', { name: 'Ada' })}</h1>
      <p>{t('cart.count', { count: 3 })}</p>
      <p>{formatNumber(1234.5)}</p>
    </main>
  );
};

export const About = ({ alternates, i18n }: AboutProps) => (
  <html dir={i18n.dir} lang={i18n.locale}>
    <Head alternates={alternates} title="About" />
    <body>
      <I18nProvider value={i18n}>
        <Greeting />
      </I18nProvider>
    </body>
  </html>
);

The payload travels with the page's other props, so the browser hydrates with the same messages and adds no extra script.

#Svelte

Call setI18n() in the page with the payload prop. It returns the page's translator and shares it with every component below, which reads it with getI18n(). Both come from @absolutejs/absolute/svelte. AbsoluteJS writes the request's lang and dir on <html> for Svelte pages.

SVELTE
<!-- src/frontend/svelte/pages/Welcome.svelte -->
<script lang="ts">
  import type { I18nPayload } from '@absolutejs/absolute/i18n';
  import { setI18n } from '@absolutejs/absolute/svelte';
  import type en from '../../../i18n/messages/en';
  import CartSummary from '../components/CartSummary.svelte';

  let { i18n }: { i18n: I18nPayload } = $props();

  const { t } = setI18n<typeof en>(i18n);
</script>

<svelte:head>
  <meta charset="utf-8" />
  <title>Welcome</title>
</svelte:head>

<main>
  <h1>{t('common.greeting', { name: 'Ada' })}</h1>
  <CartSummary count={0} />
</main>

<!-- src/frontend/svelte/components/CartSummary.svelte -->
<script lang="ts">
  import { getI18n } from '@absolutejs/absolute/svelte';
  import type en from '../../../i18n/messages/en';

  let { count }: { count: number } = $props();

  const { t } = getI18n<typeof en>();
</script>

<p>{t('cart.count', { count })}</p>
TS
.get('/:locale?/welcome', ({ i18n: requestI18n }) =>
  handleSveltePageRequest<typeof Welcome>({
    indexPath: asset(manifest, 'WelcomeIndex'),
    pagePath: asset(manifest, 'Welcome'),
    props: { i18n: requestI18n.payload(['common', 'cart']) }
  })
)

#Type Safety

Keys and ICU parameters are read from the default catalog's literal strings. No code generation is involved.

TS
const { t } = useI18n<typeof en>();

t('common.greeting', { name: 'Ada' }); // OK
t('cart.count', { count: 3 }); // OK

t('common.greting', { name: 'Ada' }); // Error: unknown key
t('cart.count'); // Error: missing { count }
t('cart.count', { count: 'three' }); // Error: count must be a number

// Error: 'updated' is missing from common
const de: Translation<typeof en> = {
  cart: { count: '...' },
  common: { greeting: '...' }
};
ArgumentParameter type
{name}string | number | bigint | Date
{count, plural, …}number (also selectordinal and number)
{when, date, …}Date | number (also time)
{kind, select, …}string

A message without arguments takes no params object. A JSON catalog still works, but TypeScript widens its strings, so only keys are checked.

#Formatting

Every translator, on the server or in a component, has the same methods. Formatters are cached per locale and options.

t(key, params)Formats the message at a dot-separated key. A key missing from the catalog renders as the key itself, and a missing parameter renders as {name}.
has(key)Whether the loaded catalog has a message at the key.
formatNumber, formatDate, formatRelativeTime, formatListIntl.NumberFormat, Intl.DateTimeFormat, Intl.RelativeTimeFormat and Intl.ListFormat for the locale.
locale, dirThe translator's locale and its text direction, 'ltr' or 'rtl'.

#hreflang & Sitemap

i18n.alternates() returns one link per locale plus x-default for the current path. Pass the list to the alternates field of Metadata. The React and Svelte Head components and generateHeadElement render it as <link rel="alternate" hreflang> tags. Under the negotiate strategy the list is empty, because every locale shares one URL.

Set sitemap.i18n with the same locales to list every page once per locale, each with xhtml:link alternates. Routes registered as /:locale?/… or /:locale/… are listed under their unprefixed path.

TS
// absolute.config.ts
import { defineConfig } from '@absolutejs/absolute';

export default defineConfig({
  sitemap: {
    baseUrl: 'https://example.com',
    i18n: { defaultLocale: 'en', locales: ['en', 'fr', 'ar'] }
  }
});

#Browser Helpers

@absolutejs/absolute/i18n holds the browser-safe pieces: defineMessages, the message formatter, the routing helpers and createTranslator. Use them for language switchers and plain scripts.

TS
import {
  createTranslator,
  formatMessage,
  localeDirection,
  localizePath,
  negotiateLocale,
  parseAcceptLanguage
} from '@absolutejs/absolute/i18n';

const routing = { defaultLocale: 'en', locales: ['en', 'fr', 'ar'] };

localizePath('/fr/about', 'en', routing); // '/about'
localizePath('/about', 'ar', routing); // '/ar/about'
negotiateLocale(parseAcceptLanguage('fr-CA,fr;q=0.9'), routing.locales, 'en'); // 'fr'
localeDirection('he-IL'); // 'rtl'
formatMessage('fr', '{count, plural, one {# fichier} other {# fichiers}}', {
  count: 2
}); // '2 fichiers'

// A translator over a payload the server sent
const { t } = createTranslator<typeof en>(payload);

The entry also exports parseMessage, alternateLinks, localeFromPath, stripLocalePrefix, matchLocale, readCookie, lookupMessage, isI18nPayload and isMessageTree, plus the i18n types.

#Outside a Request

The instance defineI18n() returns works on its own. Use it in scripts, tests and emails.

TS
import { i18n } from './i18n';

// Outside a request: scripts, tests, emails
const fr = await i18n.translator('fr');
fr.t('cart.count', { count: 1 }); // '1 article'
fr.formatList(['a', 'b', 'c']); // 'a, b et c'
fr.formatRelativeTime(-1, 'day'); // 'il y a 1 jour'

const payload = await i18n.payload('fr', ['cart']);
const setCookie = i18n.cookie('fr'); // 'locale=fr; Path=/; Max-Age=31536000; SameSite=Lax'