Easy i18n for Next.js +10
Next plugin + i18n API
- 1. About next-translate
- 2. Getting started
- 3. Configuration
- 4. API
- 5. Plurals
- 6. Use HTML inside the translation
- 7. Nested translations
- 8. Fallbacks
- 9. How to change the language
- 10. How to save the user-defined language
- 11. How to use multi-language in a page
- 12. How to use next-translate in a mono-repo
- 13. Demos
- Contributors β¨
The main goal of this library is to keep the translations as simple as possible in a Next.js environment.
Next-translate has two parts: Next.js plugin + i18n API.
Features β¨
- π γ» Works well with automatic page optimization.
- π¦ γ» Easy to use and configure.
- π γ» Basic i18n support: interpolation, plurals, useTranslation hook, Trans component...
- ποΈ γ» It loads only the necessary translations (for page and for locale).
- π¦ γ» Tiny (~1kb) and tree shakable. No dependencies.
In the configuration file, you specify each page that namespaces needs:
i18n.json
{
"pages": {
"*": ["common"],
"/": ["home"],
"/cart": ["cart"],
"/content/[slug]": ["content"],
"rgx:^/account": ["account"]
}
// rest of config here...
}
Read here about how to add the namespaces JSON files.
Next-translate ensures that each page only has its namespaces with the current language. So if we have 100 locales, only 1 will be loaded.
In order to do this we use a webpack loader that loads the necessary translation files inside the Next.js methods (getStaticProps, getServerSideProps or getInitialProps). If you have one of these methods already on your page, the webpack loader will use your own method, but the defaults it will use are:
getStaticProps
. This is the default method used on most pages, unless it is a page specified in the next two points. This is for performance, so the calculations are done in build time instead of request time.getServerSideProps
. This is the default method for dynamic pages like[slug].js
or[...catchall].js
. This is because for these pages it is necessary to define thegetStaticPaths
and there is no knowledge of how the slugs should be for each locale. Likewise, how is it by default, only that you write the getStaticPaths then it will already use the getStaticProps to load the translations.getInitialProps
. This is the default method for these pages that use a HoC. This is in order to avoid conflicts because HoC could overwrite agetInitialProps
.
This whole process is transparent, so in your pages you can directly consume the useTranslate
hook to use the namespaces, and you don't need to do anything else.
If for some reason you use a getInitialProps
in your _app.js
file, then the translations will only be loaded into your getInitialProps
from _app.js
. We recommend that for optimization reasons you don't use this approach unless it is absolutely necessary.
yarn add next-translate
In your next.config.js file:
const nextTranslate = require('next-translate')
module.exports = nextTranslate()
Or if you already have next.config.js file and want to keep the changes in it, pass the config object to the nextTranslate()
. For example for webpack you could do it like this:
const nextTranslate = require('next-translate')
module.exports = nextTranslate({
webpack: (config, { isServer, webpack }) => {
return config;
}
})
Add a configuration file i18n.json
(or i18n.js
with module.exports
) in the root of the project. Each page should have its namespaces. Take a look at it in the config section for more details.
{
"locales": ["en", "ca", "es"],
"defaultLocale": "en",
"pages": {
"*": ["common"],
"/": ["home", "example"],
"/about": ["about"]
}
}
In the configuration file you can use both the configuration that we specified here and the own features about internationalization of Next.js 10.
By default the namespaces are specified on the /locales root directory in this way:
/locales
.
βββ ca
βΒ Β βββ common.json
βΒ Β βββ home.json
βββ en
βΒ Β βββ common.json
βΒ Β βββ home.json
βββ es
βββ common.json
βββ home.json
Each filename matches the namespace specified on the pages
config property, while each file content should be similar to this:
{
"title": "Hello world",
"variable-example": "Using a variable {{count}}"
}
However, you can use another destination to save your namespaces files using loadLocaleFrom configuration property:
i18n.js
{
// ...rest of config
"loadLocaleFrom": (lang, ns) =>
// You can use a dynamic import, fetch, whatever. You should
// return a Promise with the JSON file.
import(`./myTranslationsFiles/${lang}/${ns}.json`).then((m) => m.default),
}
Then, use the translations in the page and its components:
pages/example.js
import useTranslation from 'next-translate/useTranslation'
export default function ExamplePage() {
const { t, lang } = useTranslation('common')
const example = t('variable-example', { count: 42 })
return <div>{example}</div> // <div>Using a variable 42</div>
}
You can consume the translations directly on your pages, you don't have to worry about loading the namespaces files manually on each page. The next-translate plugin loads only the namespaces that the page needs and only with the current language.
In the configuration file you can use both the configuration that we specified here and the own features about internationalization of Next.js 10.
Option | Description | Type | Default |
---|---|---|---|
defaultLocale |
ISO of the default locale ("en" as default). | string |
"en" |
locales |
An array with all the languages to use in the project. | string[] |
[] |
loadLocaleFrom |
Change the way you load the namespaces. | function that returns a Promise with the JSON . |
By default is loading the namespaces from locales root directory. |
pages |
An object that defines the namespaces used in each page. Example of object: {"/": ["home", "example"]} . To add namespaces to all pages you should use the key "*" , ex: {"*": ["common"]} . It's also possible to use regex using rgx: on front: {"rgx:/form$": ["form"]} . You can also use a function instead of an array, to provide some namespaces depending on some rules, ex: { "/": ({ req, query }) => query.type === 'example' ? ['example'] : []} |
Object<string[] or function> |
{} |
logger |
Function to log the missing keys in development and production. If you are using i18n.json as config file you should change it to i18n.js . |
function |
By default the logger is a function doing a console.warn only in development. |
logBuild |
Each page has a log indicating: namespaces, current language and method used to load the namespaces. With this you can disable it. | Boolean |
true |
loader |
If you wish to disable the webpack loader and manually load the namespaces on each page, we give you the opportunity to do so by disabling this option. | Boolean |
true |
interpolation |
Change the delimeter that is used for interpolation. | {prefix: string; suffix: string} |
{prefix: '{{', suffix: '}}'} |
staticsHoc |
The HOCs we have in our API (appWithI18n), do not use hoist-non-react-statics in order not to include more kb than necessary (static values different than getInitialProps in the pages are rarely used). If you have any conflict with statics, you can add hoist-non-react-statics (or any other alternative) here. See an example. | Function |
null |
extensionsRgx |
Change the regex used by the webpack loader to find Next.js pages. | Regex |
/\.(tsx|ts|js|mjs|jsx)$/ |
Size: ~150b π¦
This hook is the recommended way to use translations in your pages / components.
- Input: string - defaultNamespace (optional)
- Output: Object { t: Function, lang: string }
Example:
import React from 'react'
import useTranslation from 'next-translate/useTranslation'
export default function Description() {
const { t, lang } = useTranslation('ns1') // default namespace (optional)
const title = t('title')
const titleFromOtherNamespace = t('ns2:title')
const description = t`description` // also works as template string
const example = t('ns2:example', { count: 3 }) // and with query params
return (
<>
<h1>{title}</h1>
<p>{description}</p>
<p>{example}</p>
<>
)
}
The t
function:
- Input:
- Output: string
Size: ~560b π¦
It's an alternative to useTranslation
hook, but in a HOC for these components that are no-functional. (Not recommended, it's better to use the useTranslation
hook.).
The withTranslation
HOC returns a Component with an extra prop named i18n
(Object { t: Function, lang: string }).
Example:
import React from 'react'
import withTranslation from 'next-translate/withTranslation'
class Description extends React.Component {
render() {
const { t, lang } = this.props.i18n
const description = t('common:description')
return <p>{description}</p>
}
}
export default withTranslation(NoFunctionalComponent)
Similar to useTranslation("common")
you can call withTranslation
with the second parameter defining a default namespace to use:
export default withTranslation(NoFunctionalComponent, "common")
Size: ~1.4kb π¦
Sometimes we need to do some translations with HTML inside the text (bolds, links, etc), the Trans
component is exactly what you need for this. We recommend to use this component only in this case, for other cases we highly recommend the usage of useTranslation
hook instead.
Example:
// The defined dictionary enter is like:
// "example": "<0>The number is <1>{{count}}</1></0>",
<Trans
i18nKey="common:example"
components={[<Component />, <b className="red" />]}
values={{ count: 42 }}
/>
Or using components
prop as a object:
// The defined dictionary enter is like:
// "example": "<component>The number is <b>{{count}}</b></component>",
<Trans
i18nKey="common:example"
components={{
component: <Component />,
b: <b className="red" />,
}}
values={{ count: 42 }}
/>
- Props:
i18nKey
- string - key of i18n entry (namespace:key)components
- Array | Object - In case of Array each index corresponds to the defined tag<0>
/<1>
. In case of object each key corresponds to the defined tag<example>
.values
- Object - query paramsfallback
- string | string[] - Optional. Fallback i18nKey if the i18nKey doesn't match.
Size: ~1.5kb π¦
The DynamicNamespaces
component is useful to load dynamic namespaces, for example, in modals.
Example:
import React from 'react'
import Trans from 'next-translate/Trans'
import DynamicNamespaces from 'next-translate/DynamicNamespaces'
export default function ExampleWithDynamicNamespace() {
return (
<DynamicNamespaces namespaces={['dynamic']} fallback="Loading...">
{/* ALSO IS POSSIBLE TO USE NAMESPACES FROM THE PAGE */}
<h1>
<Trans i18nKey="common:title" />
</h1>
{/* USING DYNAMIC NAMESPACE */}
<Trans i18nKey="dynamic:example-of-dynamic-translation" />
</DynamicNamespaces>
)
}
Remember that ['dynamic']
namespace should not be listed on pages
configuration:
pages: {
'/my-page': ['common'], // only common namespace
}
- Props:
namespaces
- string[] - list of dynamic namespaces to download - Required.fallback
- ReactNode - Fallback to display meanwhile the namespaces are loading. - Optional.dynamic
- function - By default it uses the loadLocaleFrom in the configuration to load the namespaces, but you can specify another destination. - Optional.
Size: ~1.3kb π¦
Asynchronous function to load the t
function outside components / pages. It works on both server-side and client-side.
Unlike the useTranslation hook, we can use here any namespace, it doesn't have to be a namespace defined in the "pages" configuration. It downloads the namespace indicated as a parameter on runtime.
Example inside getStaticProps
:
import getT from 'next-translate/getT'
// ...
export async function getStaticProps({ locale }) {
const t = await getT(locale, 'common')
const title = t('title')
return { props: { title } }
}
Example inside API Route:
import getT from 'next-translate/getT'
export default async function handler(req, res) {
const t = await getT(req.query.__nextLocale, 'common')
const title = t('title')
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ title }))
}
Size: ~3kb π¦
The I18nProvider
is a context provider internally used by next-translate to provide the current lang and the page namespaces. SO MAYBE YOU'LL NEVER NEED THIS.
However, it's exposed to the API because it can be useful in some cases. For example, to use multi-language translations in a page.
The I18nProvider
is accumulating the namespaces, so you can rename the new ones in order to keep the old ones.
import React from 'react'
import I18nProvider from 'next-translate/I18nProvider'
import useTranslation from 'next-translate/useTranslation'
// Import English common.json
import commonEN from '../../locales/en/common.json'
function PageContent() {
const { t, lang } = useTranslation()
console.log(lang) // -> current language
return (
<div>
<p>{t('common:example') /* Current language */}</p>
<p>{t('commonEN:example') /* Force English */}</p>
</div>
)
}
export default function Page() {
const { lang } = useTranslation()
return (
<I18nProvider lang={lang} namespaces={{ commonEN }}>
<PageContent />
</I18nProvider>
)
}
Size: ~3.7kb π¦
The appWithI18n
is internally used by next-translate. SO MAYBE YOU'LL NEVER NEED THIS. However, we expose it in the API in case you disable the webpack loader option and decide to load the namespaces manually.
If you wish not to use the webpack loader, then you should put this in your _app.js
file (and create the _app.js
file if you don't have it).
Example:
_app.js
import appWithI18n from 'next-translate/appWithI18n'
import i18nConfig from '../i18n'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
// Wraping your _app.js
export default appWithI18n(MyApp, {
...i18nConfig,
// Set to false if you want to load all the namespaces on _app.js getInitialProps
skipInitialProps: true,
})
If skipInitialProps=true
, then you should also use the loadNamespaces helper to manually load the namespaces on each page.
Size: ~1.9kb π¦
The loadNamespaces
is internally used by next-translate. SO MAYBE YOU'LL NEVER NEED THIS. However, we expose it in the API in case you disable the webpack loader option and decide to load the namespaces manually.
To load the namespaces, you must return in your pages the props that the helper provides.
import loadNamespaces from 'next-translate/loadNamespaces'
export function getStaticProps({ locale }) {
return {
props: {
...(await loadNamespaces({ locale, pathname: '/about' })),
}
}
}
π¨ To work well, it is necessary that your _app.js
will be wrapped with the appWithI18n. Also, the loadLocaleFrom
configuration property is mandatory to define it.
We support 6 plural forms (taken from CLDR Plurals page) by adding to the key this suffix (or nesting it under the key with no _
prefix):
_zero
_one
(singular)_two
(dual)_few
(paucal)_many
(also used for fractions if they have a separate class)_other
(requiredβgeneral plural formβalso used if the language only has a single form)
See more info about plurals here.
Only the last one, _other
, is required because itβs the only common plural form used in all locales.
All other plural forms depends on locale. For example English has only two: _one
and _other
(1 cat vs. 2 cats). Some languages have more, like Russian and Arabic.
In addition, we also support an exact match by specifying the number (_0
, _999
) and this works for all locales. Here is an example:
Code:
// **Note**: Only works if the name of the variable is {{count}}.
t('cart-message', { count })
Namespace:
{
"cart-message_0": "The cart is empty", // when count === 0
"cart-message_one": "The cart has only {{count}} product", // singular
"cart-message_other": "The cart has {{count}} products", // plural
"cart-message_999": "The cart is full", // when count === 999
}
or
{
"cart-message": {
"0": "The cart is empty", // when count === 0
"one": "The cart has only {{count}} product", // singular
"other": "The cart has {{count}} products", // plural
"999": "The cart is full", // when count === 999
}
}
Intl.PluralRules API is only available for modern browsers, if you want to use it in legacy browsers you should add a polyfill.
You can define HTML inside the translation this way:
{
"example-with-html": "<0>This is an example <1>using HTML</1> inside the translation</0>"
}
Example:
import Trans from 'next-translate/Trans'
// ...
const Component = (props) => <p {...props} />
// ...
<Trans
i18nKey="namespace:example-with-html"
components={[<Component />, <b className="red" />]}
/>
Rendered result:
<p>This is an example <b class="red">using HTML</b> inside the translation</p>
Each index of components
array corresponds with <index></index>
of the definition.
In the components
array, it's not necessary to pass the children of each element. Children will be calculated.
In the namespace, it's possible to define nested keys like this:
{
"nested-example": {
"very-nested": {
"nested": "Nested example!"
}
}
}
In order to use it, you should use "." as id separator:
t`namespace:nested-example.very-nested.nested`
Also is possible to use as array:
{
"array-example": [
{ "example": "Example {{count}}" },
{ "another-example": "Another example {{count}}" }
]
}
And get all the array translations with the option returnObjects
:
t('namespace:array-example', { count: 1 }, { returnObjects: true })
/*
[
{ "example": "Example 1" },
{ "another-example": "Another example 1" }
]
*/
If no translation exists you can define fallbacks (string|string[]
) to search for other translations:
const { t } = useTranslation()
const textOrFallback = t(
'ns:text',
{ count: 1 },
{
fallback: 'ns:fallback',
}
)
List of fallbacks:
const { t } = useTranslation()
const textOrFallback = t(
'ns:text',
{ count: 42 },
{
fallback: ['ns:fallback1', 'ns:fallback2'],
}
)
In Trans Component:
<Trans
i18nKey="ns:example"
components={[<Component />, <b className="red" />]}
values={{ count: 42 }}
fallback={['ns:fallback1', 'ns:fallback2']} // or string with just 1 fallback
/>
In order to change the current language you can use the Next.js navigation (Link and Router) passing the locale
prop.
An example of a possible ChangeLanguage
component using the useRouter
hook from Next.js
:
import React from 'react'
import Link from 'next/link'
import useTranslation from 'next-translate/useTranslation'
import i18nConfig from '../i18n.json'
const { locales } = i18nConfig
export default function ChangeLanguage() {
const { t, lang } = useTranslation()
return locales.map((lng) => {
if (lng === lang) return null
return (
<Link href="/" locale={lng} key={lng}>
{t(`layout:language-name-${lng}`)}
</Link>
)
})
}
You could also use setLanguage
to change the language while keeping the same page.
import React from 'react'
import setLanguage from 'next-translate/setLanguage'
export default function ChangeLanguage() {
return (
<button onClick={async () => await setLanguage('en')}>EN</button>
)
}
Another way of accessing the locales
list to change the language is using the Next.js router
. The locales
list can be accessed using the Next.js useRouter hook.
You can set a cookie named NEXT_LOCALE
with the user-defined language as value, this way a locale can be forced.
Example of hook:
import { useRouter } from 'next/router'
// ...
function usePersistLocaleCookie() {
const { locale, defaultLocale } = useRouter()
useEffect(persistLocaleCookie, [locale, defaultLocale])
function persistLocaleCookie() {
if(locale !== defaultLocale) {
const date = new Date()
const expireMs = 100 * 365 * 24 * 60 * 60 * 1000 // 100 days
date.setTime(date.getTime() + expireMs)
document.cookie = `NEXT_LOCALE=${locale};expires=${date.toUTCString()};path=/`
}
}
}
In some cases, when the page is in the current language, you may want to do some exceptions displaying some text in another language.
In this case, you can achieve this by using the I18nProvider
.
Learn how to do it here.
Next-translate uses by default the current working directory of the Node.js process (process.cwd()
). If you want to change it you can use the NEXT_TRANSLATE_PATH
environment variable. It supports both relative and absolute path.
There is a demo of next-translate
on the Next.js repo:
To use it:
npx create-next-app --example with-next-translate with-next-translate-app
# or
yarn create next-app --example with-next-translate with-next-translate-app
This demo is in this repository:
git clone [email protected]:vinissimus/next-translate.git
cd next-translate
yarn && yarn example:basic
Similar than the basic demo but with some extras: TypeScript, Webpack 5, MDX, with _app.js on top, pages located on src/pages folder, loading locales from src/translations with a different structure.
This demo is in this repository:
git clone [email protected]:vinissimus/next-translate.git
cd next-translate
yarn && yarn example:complex
Similar than the basic example but loading the page namespaces manually deactivating the webpack loader in the i18n.json config file.
We do not recommend that it be used in this way. However we give the opportunity for anyone to do so if they are not comfortable with our webpack loader.
This demo is in this repository:
git clone [email protected]:vinissimus/next-translate.git
cd next-translate
yarn && yarn example:without-loader
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!