Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
next-i18next
Advanced tools
The next-i18next package is a powerful internationalization framework for Next.js applications. It simplifies the process of adding multilingual support to your Next.js projects by integrating with the i18next library. It provides server-side rendering, automatic language detection, and easy translation management.
Basic Setup
This code demonstrates the basic setup of next-i18next. It initializes the next-i18next instance with a default language and other supported languages.
const NextI18Next = require('next-i18next').default;
const nextI18Next = new NextI18Next({
defaultLanguage: 'en',
otherLanguages: ['de', 'fr'],
});
module.exports = nextI18Next;
Translation in Components
This code shows how to use translations in a React component. The `withTranslation` higher-order component is used to inject the `t` function, which is then used to fetch the translated text.
import { withTranslation } from 'next-i18next';
const MyComponent = ({ t }) => (
<div>
<h1>{t('welcome_message')}</h1>
</div>
);
export default withTranslation('common')(MyComponent);
Server-Side Rendering
This code demonstrates how to use next-i18next with Next.js's server-side rendering. The `serverSideTranslations` function is used to load the necessary translations for the requested locale.
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
export const getStaticProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale, ['common'])),
},
});
react-i18next is a powerful internationalization framework for React applications. It is built on top of the i18next library and provides a variety of features for managing translations. Unlike next-i18next, it does not have built-in support for Next.js, so additional configuration is required for server-side rendering.
next-translate is another internationalization library for Next.js. It focuses on simplicity and ease of use, providing a zero-dependency solution for adding multilingual support to Next.js applications. Compared to next-i18next, it offers a more lightweight approach but may lack some advanced features.
i18next is a comprehensive internationalization library for JavaScript applications. It provides a wide range of features for managing translations, including support for multiple languages, pluralization, and interpolation. While it is not specific to Next.js, it can be used in conjunction with other libraries to achieve similar functionality to next-i18next.
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.
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.
Easy to set up, easy to use: setup only takes a few steps, and configuration is simple.
No other requirements: next-i18next
simplifies internationalisation for your NextJs app without extra dependencies.
Production ready: next-i18next
supports passing translations and configuration options into pages as props with SSG/SSR support.
Your next-i18next.config.js
file will provide configuration for next-i18next
.
After configuration, appWithTranslation
allows us to use the t
(translate) function in our components via hooks.
Then we add serverSideTranslation
to getStaticProps or getServerSideProps (depending on your case) in our page-level components.
Now our NextJs app is fully translatable!
yarn add next-i18next
You need to also have react
and next
installed.
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.
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:
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
.
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 async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, ['common', 'footer'])),
// Will be passed to the page component as props
},
};
}
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.
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>
);
};
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.
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'),
};
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);
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import nextI18NextConfig from '../next-i18next.config.js';
export const getStaticProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(
locale,
['common', 'footer'],
nextI18NextConfig
)),
},
});
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.
To migrate from previous versions to the version 8, check out the v8-migration guide
For Docker deployment, note that if you use the Dockerfile
from Next.js docs do not forget to copy next.config.js
and next-i18next.config.js
into the Docker image.
COPY --from=builder /app/next.config.js ./next.config.js
COPY --from=builder /app/next-i18next.config.js ./next-i18next.config.js
Thanks goes to these wonderful people (emoji key):
Rob Capellini 💻 ⚠️ | Alexander Kachkaev 📢 💬 🤔 💻 ⚠️ | Mathias Wøbbe 💻 🤔 ⚠️ | Lucas Feliciano 🤔 👀 | Ryan Leung 💻 | Nathan Friemel 💻 📖 💡 🤔 |
This project follows the all-contributors specification. Contributions of any kind welcome!
FAQs
The easiest way to translate your NextJs apps.
The npm package next-i18next receives a total of 365,353 weekly downloads. As such, next-i18next popularity was classified as popular.
We found that next-i18next demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.