Inline Translations

tx

API reference for the tx string translation function

Overview

The tx function is a server-side function for translating strings.

await tx('Hello, world!'); // returns 'Hola, mundo!'

Runtime translation: tx translations occur at runtime. This means translation happens live, so you can translate content that’s only available at runtime.

Reference

Parameters

Prop

Type

NameDescription
contentThe string that needs to be translated.
optionsTranslation options to customise the behaviour of tx. See RuntimeTranslationOptions.

Returns

A promise that resolves to a string containing the translated content, or the original content if no translation is required.


Behaviour

The tx function translates strings at runtime. This means translations are performed live, so you can translate content that’s only known at runtime. The trade‑off is a delay: on‑demand translations take significantly longer to load.

Our advice is to translate everything you can at build time using getGT, useGT, or <T>, and only use on‑demand translations, like tx and <Tx>, when necessary.

Make sure to follow the deployment guide here.


Example

Basic usage

You can use tx to translate strings.

src/components/translateGreeting.jsx
import { tx } from 'gt-next/server';

export default async function translateGreeting() {
    return await tx("Hello, world!"); 
}

Adding context

You can customise the translation by providing context to be taken into account during translation.

TranslateWithOptions.jsx
import { tx } from 'gt-next/server';

export default async function TranslateWithOptions() {
    return await tx("Hello, world!", {
      $context: 'Use informal translation'
    });
}

Using Variables

To pass values into your string, you must (1) assign an identifier and (2) reference that identifier in the object you pass.

translateWithVariables.js
import { tx } from 'gt-next/server';

export default async function translateWithVariables() {
  return await tx("The price is {price, number, ::currency/GBP}", {
    price: 29.99,
  });
}

Specifying a locale

You can specify a locale to use for the translation. By default, the locale is set to the user’s preferred language.

translateWithLocale.js
import { tx } from 'gt-next/server';

export default async function translateWithLocale() {
    return await tx("Hello, world!", { $locale: 'fr' }); 
}

Notes

  • tx is for server-side use only and cannot be used in client-side components.
  • Translations with tx occur at runtime, meaning they’re applied live. This is significantly slower than translations at build time.

Next steps

How is this guide?

tx