/next-i18next

The easiest way to translate your NextJs apps.

Primary LanguageTypeScriptMIT LicenseMIT

next-i18next

npm version CircleCI Package Quality

The easiest way to translate your NextJs apps.

If you are using next-i18next in production, please consider sponsoring the package with any amount you think appropriate.

What is this?

Although NextJs provides internationalised routing directly, it does not handle any management of translation content, or the actual translation functionality itself. All NextJs does is keep your locales and URLs in sync.

To complement this, next-i18next provides the remaining functionality – management of translation content, and components/hooks to translate your React components – while fully supporting SSG/SSR, multiple namespaces, codesplitting, etc.

While next-i18next uses i18next and react-i18next under the hood, users of next-i18next simply need to include their translation content as JSON files and don't have to worry about much else.

A live demo is available here. This demo app is the simple example - nothing more, nothing less.

Setup

1. Installation

yarn add next-i18next

You need to also have react and next installed.

2. Translation content

By default, next-i18next expects your translations to be organised as such:

.
└── public
    └── locales
        ├── en
        |   └── common.json
        └── de
            └── common.json

This structure can also be seen in the simple example.

If you want to structure your translations/namespaces in a custom way, you will need to pass modified localePath and localeStructure values into the initialisation config.

3. Project setup

First, create a next-i18next.config.js file in the root of your project. The syntax for the nested i18n object comes from NextJs directly.

This tells next-i18next what your defaultLocale and other locales are, so that it can preload translations on the server:

next-i18next.config.js

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'de'],
  },
}

Now, create or modify your next.config.js file, by passing the i18n object into your next.config.js file, to enable localised URL routing:

next.config.js

const { i18n } = require('./next-i18next.config')

module.exports = {
  i18n,
}

There are three functions that next-i18next exports, which you will need to use to translate your project:

appWithTranslation

This is a HOC which wraps your _app:

import { appWithTranslation } from 'next-i18next'

const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />

export default appWithTranslation(MyApp)

The appWithTranslation HOC is primarily responsible for adding a I18nextProvider.

serverSideTranslations

This is an async function that you need to include on your page-level components, via either getStaticProps or getServerSideProps (depending on your use case):

import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

export const getStaticProps = async ({ locale }) => ({
  props: {
    ...await serverSideTranslations(locale, ['common', 'footer']),
  }
})

Note that serverSideTranslations must be imported from next-i18next/serverSideTranslations – this is a separate module that contains NodeJs-specific code.

Also, note that serverSideTranslations is not compatible with getInitialProps, as it only can execute in a server environment, whereas getInitialProps is called on the client side when navigating between pages.

The serverSideTranslations HOC is primarily responsible for passing translations and configuration options into pages, as props.

useTranslation

This is the hook which you'll actually use to do the translation itself. The useTranslation hook comes from react-i18next, but can be imported from next-i18next directly:

import { useTranslation } from 'next-i18next'

export const Footer = () => {

  const { t } = useTranslation('footer')

  return (
    <footer>
      <p>
        {t('description')}
      </p>
    </footer>
  )
}

4. Declaring namespace dependencies

By default, next-i18next will send all your namespaces down to the client on each initial request. This can be an appropriate approach for smaller apps with less content, but a lot of apps will benefit from splitting namespaces based on route.

To do that, you can pass an array of required namespaces for each page into serverSideTranslations. You can see this approach in examples/simple/pages/index.js.

Note: useTranslation provides namespaces to the component that you use it in. However, serverSideTranslations provides the total available namespaces to the entire React tree and belongs on the page level. Both are required.

5. Advanced configuration

Passing other config options

If you need to modify more advanced configuration options, you can pass them via next-i18next.config.js. For example:

const path = require('path')

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'de'],
  },
  localePath: path.resolve('./my/custom/path')
}

Unserialisable configs

Some i18next plugins (which you can pass into config.use) are unserialisable, as they contain functions and other JavaScript primitives.

You may run into this if your use case is more advanced. You'll see NextJs throw an error like:

Error: Error serializing `._nextI18Next.userConfig.use[0].process` returned from `getStaticProps` in "/my-page".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.

To fix this, you'll need to set config.serializeConfig to false, and manually pass your config into appWithTranslation:

import { appWithTranslation } from 'next-i18next'
import nextI18NextConfig from '../next-i18next.config.js'

const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />

export default appWithTranslation(MyApp, nextI18NextConfig)

Options

Key Default value
defaultNS 'common'
localeExtension 'json'
localePath './public/locales'
localeStructure '{{lng}}/{{ns}}'
serializeConfig true
strictMode true
use (for plugins) []

All other i18next options can be passed in as well.

Contributors

Thanks goes to these wonderful people (emoji key):

Rob Capellini
Rob Capellini

💻 ⚠️
Alexander Kachkaev
Alexander Kachkaev

📢 💬 🤔 💻 ⚠️
Mathias Wøbbe
Mathias Wøbbe

💻 🤔 ⚠️
Lucas Feliciano
Lucas Feliciano

🤔 👀
Ryan Leung
Ryan Leung

💻
Nathan Friemel
Nathan Friemel

💻 📖 💡 🤔

This project follows the all-contributors specification. Contributions of any kind welcome!

Sponsors