Implementing multilingual support is an essential part of developing globally oriented web applications. Next.js offers flexible options to manage and present multilingual content and translations.
As of version 10, Next.js supports native international routes (i18n
routing). This functionality makes it possible to provide different
language versions of the same page under different paths,
e.g. /en/about
and /de/about
for English and
German versions of an “About us” page respectively.
The i18n support is configured in the next.config.js
file. Here you can define the supported languages and the default
locale:
.exports = {
modulei18n: {
locales: ['en', 'de', 'fr'],
defaultLocale: 'en',
,
}; }
For the actual translation of the content, it is advisable to use proven localization libraries. Popular options are:
react-i18next: A React integration of the i18next library, which offers extensive translation functions and localization support.
next-i18next: Builds on react-i18next and provides additional integrations specifically for Next.js, such as server-side rendering and route localization.
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <p>{t('key_for_translation')}</p>;
}
Translation resources can be loaded dynamically to reduce the
application size and optimize loading times. Libraries such as
react-i18next
support loading translation files via network
request or by importing JSON files.
The localization of date and time information can be achieved by
using libraries such as date-fns
or moment
.
These libraries provide functions for formatting dates in different
languages and cultures.
It is important to consider SEO aspects for multilingual pages. This
includes setting hreflang
tags for different language
versions and ensuring that search engines index the different language
versions correctly.
Create a simple multilingual Next.js application that includes the following:
Page structure: Two pages - a home page
(index.js
) and an “About Us” page
(about.js
).
Multilingual support: English and German.
Language switching: An option to switch between English and German.
4 Content localization: Use
next-i18next
to translate text content on both pages.
hreflang
tags for both languages.Create a new Next.js project with create-next-app
.
Install next-i18next
for the translation
functionality.
Configure next-i18next
and i18n support in
next.config.js
.
Create localization files for English and German.
Implement the two pages and integrate the localization.
Add a function to switch the language.
Implement hreflang
tags for both languages.