Rendering i18n messages
The main part of handling internationalization (typically referred to as i18n) in your Next.js app is to provide messages based on the language of the user.
Terminology
- Locale: We use this term to describe an identifier that contains the language and formatting preferences of users. Apart from the language, a locale can include optional regional information (e.g.
en-US
). Locales are specified as IETF BCP 47 language tags (opens in a new tab). - Messages: These are collections of namespace-label pairs that are grouped by locale (e.g.
en-US.json
).
Structuring messages
To group your messages within a locale, it's recommended to use component names as namespaces and embrace them as the primary unit of code organization in your app. You can of course also use a different structure, depending on what suits your app best.
{
"About": {
"title": "About us"
}
}
You can render messages from within a React component via the useTranslations
hook:
import {useTranslations} from 'next-intl';
function About() {
const t = useTranslations('About');
return <h1>{t('title')}</h1>;
}
To retrieve all available messages in a component, you can omit the namespace path:
const t = useTranslations();
t('About.title');
How can I provide more structure for messages?
Optionally, you can structure your messages as nested objects.
{
"auth": {
"SignUp": {
"title": "Sign up",
"form": {
"placeholder": "Please enter your name",
"submit": "Submit"
}
}
}
}
import {useTranslations} from 'next-intl';
function SignUp() {
// Provide the lowest common denominator that contains
// all messages this component needs to consume.
const t = useTranslations('auth.SignUp');
return (
<>
<h1>{t('title')}</h1>
<form>
<input
// The remaining hierarchy can be resolved by
// using `.` to access nested messages.
placeholder={t('form.placeholder')}
/>
<button type="submit">{t('form.submit')}</button>
</form>
</>
);
}
How can I reuse messages?
As your app grows, you'll want to reuse messages among your components. If you use component names as namespaces to structure your messages, you'll automatically benefit from reusable messages by reusing your components.
Examples:
- You're displaying products in your app and often need to resolve a category identifier to a human readable label (e.g.
new
→ "Just in"). To ensure consistency, you can add aProductCategory
component that turns thecategory
into a styled badge. - You commonly need a dialog that displays a "confirm" and "cancel" button. In this case, consider adding a
ConfirmDialog
component to reuse the messages along with the functionality.
There might be cases where you want to use the same message in different components, but there's no reasonable opportunity for sharing the message via a component. This might be symptom that these components should use separate messages, even if they happen to be the same for the time being. By using separate labels, you gain the flexibility to use more specific labels (e.g. "not now" instead of "cancel").
For edge cases where the reuse of messages among different components is hard to achieve with shared components, you can either use messages from different namespaces via useTranslations()
, or you can consider adding a hook that shares the translation behavior:
export default function useLocaleLabel() {
const t = useTranslations('useLocaleLabel');
function getLocaleLabel(locale: 'en' | 'de') {
return t('label', {locale});
}
return getLocaleLabel;
}
{
"useLocaleLabel": {
"label": "{locale, select, en {English} de {German} other {Unknown}}"
}
}
How can I use translations outside of components?
next-intl
is heavily based on the useTranslations
API which is intended to consume translations from within React components. This may seem like a limitation, but this is intentional and aims to encourage the use of proven patterns that avoid potential issues—especially if they are easy to overlook.
If you're interested to dive deeper into this topic, there's a blog post that discusses the background of this design decision: How (not) to use translations outside of React components.
There's one exception however: Using next-intl
with the Next.js Metadata API and Route Handlers.
Can I use a different style for structuring my messages?
Namespace keys can not contain the character "." as this is used to express nesting—all other characters are fine to use.
If you're migrating from a flat structure that uses "." in message keys, you can convert your messages to a nested structure as follows:
import {set} from 'lodash';
const input = {
'one.one': '1.1',
'one.two': '1.2',
'two.one.one': '2.1.1'
};
const output = Object.entries(input).reduce(
(acc, [key, value]) => set(acc, key, value),
{}
);
Output:
{
"one": {
"one": "1.1",
"two": "1.2"
},
"two": {
"one": {
"one": "2.1.1"
}
}
}
This keeps the hierarchy while removing the redundancy of repeated parent keys. You can either execute this is in a one-off script or as before passing messages to next-intl
.
If you've previously used human readable sentences for keys, you can theoretically map the .
character to a different one (e.g. _
) before passing the messages to next-intl
, but it's generally recommended to use IDs as keys. You can still view human readable labels from your messages in your editor by using a VSCode integration in case that's your primary motivation for using human readable keys.
Rendering ICU messages
next-intl
uses ICU message syntax (opens in a new tab) that allows you to express language nuances and separates state handling within messages from your app code.
To work with ICU messages, it can be helpful to use an editor that supports this syntax. E.g. the Crowdin Editor (opens in a new tab) can be used by translators to work on translations without having to change app code.
Static messages
Static messages will be used as-is:
"message": "Hello world!"
t('message'); // "Hello world!"
Interpolation of dynamic values
Dynamic values can be inserted into messages by using curly braces:
"message": "Hello {name}!"
t('message', {name: 'Jane'}); // "Hello Jane!"
Which characters are supported for value names?
Value names are required to be alphanumeric and can contain underscores. All other characters, including dashes, are not supported.
Cardinal pluralization
To express the pluralization of a given number of items, the plural
argument can be used:
"message": "You have {count, plural, =0 {no followers yet} =1 {one follower} other {# followers}}."
t('message', {count: 3580}); // "You have 3,580 followers."
Note that by using the #
marker, the value will be formatted as a number.
Which plural forms are supported?
Languages have different rules for pluralization and your messages should reflect these rules.
For example, English has two forms: One for the singular (e.g. "1 follower") and one for everything else (e.g. "0 followers" and "2 followers"). In contrast, Chinese only has one form, while Arabic has six.
The other aspect to consider is that from a usability perspective, it can be helpful to consider additional cases on top—most commonly the special case for zero (e.g. "No followers yet" instead of "0 followers").
While you can always use the =value
syntax to match a specific number (e.g. =0
), you can choose from the following tags depending on what grammar rules apply to a given language:
zero
: For languages with zero-item grammar (e.g., Latvian, Welsh).one
: For languages with singular-item grammar (e.g., English, German).two
: For languages with dual-item grammar (e.g., Arabic, Welsh).few
: For languages with grammar specific to a small number of items (e.g., Arabic, Croatian).many
: For languages with grammar specific to a larger number of items (e.g., Arabic, Croatian).other
: Used when the value doesn't match other plural categories.
next-intl
uses Intl.PluralRules
(opens in a new tab) to detect the correct tag that should be used for a given number. The exact range that few
and many
applies to varies depending on the locale (see the language plural rules table in the Unicode CLDR (opens in a new tab)).
Ordinal pluralization
To apply pluralization based on an order of items, the selectordinal
argument can be used:
"message": "It's your {year, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} birthday!"
Which plural forms are supported?
Depending on the language, different forms of ordinal pluralization are supported.
For example, English has four forms: "th", "st", "nd" and "rd" (e.g. 1st, 2nd, 3rd, 4th … 11th, 12th, 13th … 21st, 22nd, 23rd, 24th, etc.). In contrast, both Chinese and Arabic use only one form for ordinal numbers.
next-intl
uses Intl.PluralRules
(opens in a new tab) to detect the correct tag that should be used for a given number.
These tags are supported:
zero
: For languages with zero-item grammar (e.g., Latvian, Welsh).one
: For languages with singular-item grammar (e.g., English, German).two
: For languages with dual-item grammar (e.g., Arabic, Welsh).few
: For languages with grammar specific to a small number of items (e.g., Arabic, Polish, Croatian).many
: For languages with grammar specific to a larger number of items (e.g., Arabic, Polish, Croatian).other
: Used when the value doesn't match other plural categories.
The exact range that few
and many
applies to varies depending on the locale (see the language plural rules table in the Unicode CLDR (opens in a new tab)).
To match a specific number, next-intl
additionally supports the special =value
syntax (e.g. =3
) that always takes precedence.
Selecting enum-based values
To map identifiers to human readable labels, you can use the select
argument:
"message": "{gender, select, female {She} male {He} other {They}} is online."
t('message', {gender: 'female'}); // "She is online."
Note: The other
case is required and will be used when none of the specific values match.
Which characters are supported for select values?
Values are required to be alphanumeric and can contain underscores. All other characters, including dashes, are not supported.
Therefore, e.g. when you're mapping a locale to a human readable string, you should map the dash to an underscore first:
"label": "{locale, select, en_GB {British English} en_US {American English} other {Unknown}"
const locale = 'en-GB';
t('message', {locale: locale.replaceAll('-', '_')};
Escaping
Since curly braces are used for interpolating dynamic values, you can escape them with the '
marker to use the actual symbol in messages:
"message": "Escape curly braces with single quotes (e.g. '{name'})"
t('message'); // "Escape curly braces with single quotes (e.g. {name})"
Rich text
You can format rich text with custom tags and map them to React components:
{
"message": "Please refer to <guidelines>the guidelines</guidelines>."
}
// Returns `<>Please refer to <a href="/guidelines">the guidelines</a>.</>`
t.rich('message', {
guidelines: (chunks) => <a href="/guidelines">{chunks}</a>
});
Tags can be arbitrarily nested (e.g. This is <important><very>very</very> important</important>
).
How can I reuse a tag across my app?
If you want to use the same tag across your app, you can configure it via default translation values.
How can I use "self-closing" tags without any chunks?
Messages can use tags without any chunks as children, but syntax-wise, a closing tag is required by the ICU parser:
{
"message": "Hello,<br></br>how are you?"
}
t.rich('message', {
br: () => <br />
});
How can I pass attributes to tags?
Attributes can only be set on the call site, not within messages:
{
"message": "Go to <profile>my profile</profile>"
}
t.rich('message', {
profile: (chunks) => <Link href="/profile">{chunks}</Link>
});
For the use case of localizing pathnames, consider using createLocalizedPathnamesNavigation
.
In case you have attribute values that are required to be configured as part of your messages, you can retrieve them from a separate message and pass them to another one as an attribute:
{
"message": "See this <partner>partner website</partner>.",
"partnerHref": "https://partner.example.com"
}
t.rich('message', {
partner: (chunks) => <a href={t('partnerHref')}>{chunks}</a>
});
HTML markup
To render rich text, you typically want to use rich text formatting. However, if you have a use case where you need to emit raw HTML markup, you can use the t.markup
function:
{
"markup": "This is <important>important</important>"
}
// Returns 'This is <b>important</b>'
t.markup('markup', {
important: (chunks) => `<b>${chunks}</b>`
});
Note that unlike t.rich
, the provided markup functions accept chunks
as a string
and also return a string
where the chunks
are wrapped accordingly.
Raw messages
Messages are always parsed and therefore e.g. for rich text formatting you need to supply the necessary tags. If you want to avoid the parsing, e.g. because you have raw HTML stored in a message, there's a separate API for this use case:
{
"content": "<h1>Headline<h1><p>This is raw HTML</p>"
}
<div dangerouslySetInnerHTML={{__html: t.raw('content')}} />
Important: You should always sanitize the content that you pass to
dangerouslySetInnerHTML
(opens in a new tab)
to avoid cross-site scripting attacks.
The value of a raw message can be any valid JSON value: strings, booleans, objects and arrays.
Arrays of messages
If you need to render a list of messages, the recommended approach is to map an array of keys to the corresponding messages:
{
"CompanyStats": {
"yearsOfService": {
"title": "Years of service",
"value": "34"
},
"happyClients": {
"title": "Happy clients",
"value": "1.000+"
},
"partners": {
"title": "Products",
"value": "5.000+"
}
}
}
import {useTranslations} from 'next-intl';
function CompanyStats() {
const t = useTranslations('CompanyStats');
const keys = ['yearsOfService', 'happyClients', 'partners'] as const;
return (
<ul>
{keys.map((key) => (
<li key={key}>
<h2>{t(`${key}.title`)}</h2>
<p>{t(`${key}.value`)}</p>
</li>
))}
</ul>
);
}
What if the amount of items varies depending on the locale?
To dynamically iterate over all keys of a namespace, you can use the useMessages
hook to retrieve all messages of a given namespace and extract the keys from there:
import {useTranslations, useMessages} from 'next-intl';
function CompanyStats() {
const t = useTranslations('CompanyStats');
const messages = useMessages();
const keys = Object.keys(messages.CompanyStats);
return (
<ul>
{keys.map((key) => (
<li key={key}>
<h2>{t(`${key}.title`)}</h2>
<p>{t(`${key}.value`)}</p>
</li>
))}
</ul>
);
}
Right-to-left languages
Languages such as Arabic, Hebrew and Persian use right-to-left script (opens in a new tab) (often abbreviated as RTL). For these languages, writing begins on the right side of the page and continues to the left.
Example:
النص في اللغة العربية _مثلا_ يُقرأ من اليمين لليسار
In addition to providing translated messages, proper RTL localization requires:
- Providing the
dir
attribute (opens in a new tab) on the document - Layout mirroring, e.g. by using CSS logical properties (opens in a new tab)
- Element mirroring, e.g. by customizing icons
To handle these cases in your components, you can use the rtl-detect
(opens in a new tab) package:
import {getLangDir} from 'rtl-detect';
export default async function RootLayout(/* ... */) {
const locale = await getLocale();
const direction = getLangDir(locale);
return (
<html lang={locale} dir={direction}>
{/* ... */}
</html>
);
}
import {useTranslations} from 'next-intl';
import {getLangDir} from 'rtl-detect';
export default function Breadcrumbs({children, params}) {
const t = useTranslations('Breadcrumbs');
const locale = useLocale();
const direction = getLangDir(locale);
return (
<div style={{display: 'flex'}}>
<p>{t('home')}</p>
<div style={{marginInlineStart: 10}}>
{direction === 'ltr' ? <ArrowRight /> : <ArrowLeft />}
</div>
<p style={{marginInlineStart: 10}}>{t('about')}</p>
</div>
);
}