- I18next is used for internationalization.
- Next.js's internationalized routing feature is enabled. Toggling between languages is done by changing the URL's path prefix (e.g.
/about
➡️/es/about
). - Configuration for the i18n routing and i18next libraries are located in
next-i18next.config.js
. - storybook-react-i18next adds a globe icon to Storybook's toolbar for toggling languages.
- Translations are managed in the
public/locales
directory, where each language has its own directory (e.g.en
andes
). - Namespaces can be used to organize translations into smaller files. For large sites, it's common to create a namespace for each controller, page, or feature (whatever level makes most sense).
- There are a number of built-in formatters based on JS's
Intl
API that can be used in locale strings, and custom formatters can be added as well. See the i18next formatting docs for details.
-
serverSideTranslations
must be called ingetStaticProps
orgetServerSideProps
to load translations for a page.import type { GetServerSideProps } from "next"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; export const getServerSideProps: GetServerSideProps = async ({ locale }) => { // serverSideTranslations takes an optional second argument to limit // which namespaces are sent to the client const translations = await serverSideTranslations(locale ?? "en"); return { props: { ...translations } }; };
Note that
serverSideTranslations
needs imported in the same file as thegetServerSideProps
/getStaticProps
function, so that Next.js properly excludes it from the client-side bundle, where Node.js APIs (e.g.fs
) aren't available. -
Then use the
useTranslation
hook'st()
method, or theTrans
component to render localized strings.import { Trans, useTranslation } from "next-i18next"; const Page = () => { // Optionally pass in the namespace of the translation file (e.g. common) to use const { t } = useTranslation("common"); return ( <> <h1>{t("About.title")}</h1> <Trans i18nKey="About.summary" /> </> ); };
Refer to the i18next and react-i18next documentation for more usage docs.
- Edit
next-i18next.config.js
and add the language tolocales
, using the BCP47 language tag (e.g.en
ores
). - Add a language folder, using the same BCP47 language tag:
mkdir -p public/locales/<lang>
- Add a language file:
touch public/locales/<lang>/common.json
and add the translated content. The JSON structure should be the same across languages. However, non-default languages can omit keys, in which case the default language will be used as a fallback. - Optionally, add a label for the language to the
locales
object in.storybook/preview.js