General Translation  
Next.jsStrings

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 will be performed live, so you can translate content known at runtime.

Reference

Parameters

PropTypeDefault
content
string
-
options?
RuntimeTranslationOptions
{}
NameDescription
contentThe string that needs to be translated.
optionsTranslation options to customize the behavior of tx(). See RuntimeTranslationOptions.

Returns

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


Behavior

The tx() function translates strings at runtime. This means that translations are performed live, so you can translate content that is only known at runtime. The trade off is that there is a delay while waiting for an on-demand translation to load is significantly slower.

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 customize the translation by providing a context to be considered when translating.

TranslateWithOptions.jsx
import { tx } from 'gt-next/server';
 
export default async function TranslateWithOptions() {
    return await tx("Hello, world!", {
        context: 'Translate informally'
    });
}

Using Variables

In order to pass values to your string, you must (1) assign an identifier and (2) reference the identifier in the variables field.

translateWithVariables.js
import { tx } from 'gt-next/server';
 
export default async function translateWithVariables() {
    return await tx("The cost is {price}", {
        variables: { price : 29.99 },
        variableOptions: { price : { style: 'currency', currency: 'MXN' } }
    });
}

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() exclusively for server-side usage and cannot be used in client-side components.
  • Translations with tx() occur at runtime, meaning they are translated live. This is significantly slower than translations at build time.

Next Steps

On this page