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.
next-i18next
is a plugin for Next.js projects that allows you to get translations up and running quickly and easily, while fully supporting SSR, multiple namespaces with 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.
yarn add next-i18next
By default, next-i18next
expects your translations to be organised as such:
.
├── static
├── en
| └── common.json
└── de
└── common.json
This structure can also be seen in the example directory.
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.
The default export of next-i18next
is a class constructor, into which you pass your config options. The resulting class has all the methods you will need to translate your app:
import NextI18Next from 'next-i18next'
const options = {}
export default new NextI18Next(options)
A full list of options can be seen here.
It's recommended to export this NextI18Next
instance from a single file in your project, where you can continually import it from to use the class methods as needed. You can see this approach in the example/i18n.js file.
After creating and exporting your NextI18Next
instance, you need to take the following steps to get things working:
_app.js
file inside your pages
directory, and wrap it with the NextI18Next.appWithTranslation
higher order component (HOC). You can see this approach in the example/pages/_app.js.server.js
file inside your root directory, initialise an express server, and pass both the express server and NextJs app into NextI18Next.nextI18NextMiddleware
. You can see this approach in the example/server.jsThat's it! Your app is ready to go. You can now use the NextI18Next.withNamespaces
HOC to make your components or pages translatable, based on namespaces:
import React from 'react'
// This is our initialised `NextI18Next` instance
import { withNamespaces } from '../i18n'
class Footer extends React.Component {
render() {
return (
<footer>{this.props.t('description')}</footer>
)
}
}
export default withNamespaces('footer')(Footer)
One of the main features of this package, besides translation itself, are locale subpaths. It's easiest to explain by example:
myapp.com ---> Homepage in default lang
myapp.com/de/ ---> Homepage in German
This functionality is not enabled by default, and must be passed as an option into the NextI18Next
constructor:
new NextI18Next({ localeSubpaths: true })
Now, all your page routes will be duplicated across all your non-default language subpaths. If our static/locales
folder included fr
, de
, and es
translation directories, we will automatically get:
myapp.com
myapp.com/fr/
myapp.com/de/
myapp.com/es/
The main "gotcha" with locale subpaths is routing. We want to be able to route to "naked" routes, and not have to worry about the locale subpath part of the route:
<Link href='/some-page'>
With this link, we would expect someone whose language is set to French to automatically be directed to /fr/some-page
.
To do that, we must import Link
from your NextI18Next
, not next/router:
import React from 'react'
// This is our initialised `NextI18Next` instance
import { Link } from '../i18n'
class SomeLink extends React.Component {
render() {
return (
<Link href='/some-page'>
This will magically prepend locale subpaths
</Link>
)
}
}
Key | Default value |
---|---|
defaultLanguage | "en" |
otherLanguages | [] |
localePath | 'static/locales' |
localeStructure | '{{lng}}/{{ns}}' |
localeSubpaths | false |
defaultNS | 'common' |
next export
will result in a clientside only React application.i18next-express-middleware
exists.Please do! All PRs and issues will be thoroughly reviewed.
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.