Next.js Internationalization (i18n) with next-i18next and Intlayer

    Both next-i18next and Intlayer are open-source internationalization (i18n) frameworks designed for Next.js applications. They are widely used for managing translations, localization, and language switching in software projects.

    Both solutions include three principal notions:

    1. Content Declaration: The method for defining the translatable content of your application.

      • Named resource in the case of i18next, the content declaration is a structured JSON object containing key-value pairs for translations in one or more languages. See i18next documentation for more information.
      • Named content declaration file in the case of Intlayer, the content declaration can be a JSON, JS, or TS file exporting the structured data. See Intlayer documentation for more information.
    2. Utilities: Tools to build and interpret content declarations in the application, such as getI18n(), useCurrentLocale(), or useChangeLocale() for next-i18next, and useIntlayer() or useLocale() for Intlayer.

    3. Plugins and Middlewares: Features for managing URL redirection, bundling optimization, and more, such as next-i18next/middleware for next-i18next or intlayerMiddleware for Intlayer.

    Intlayer vs. i18next: Key Differences

    To explore the differences between i18next and Intlayer, check out our next-i18next vs. next-intl vs. Intlayer blog post.

    How to Generate next-i18next Dictionaries with Intlayer

    Why Use Intlayer with next-i18next?

    Intlayer content declaration files generally offer a better developer experience. They are more flexible and maintainable due to two main advantages:

    1. Flexible Placement: An Intlayer content declaration file can be placed anywhere in the application's file tree, simplifying the management of duplicated or deleted components without leaving unused content declarations.

      Example file structures:

      bash
      .└── src    └── components        └── MyComponent            ├── index.content.ts # Content declaration file            └── index.tsx
    2. Centralized Translations: Intlayer stores all translations in a single file, ensuring no translation is missing. When using TypeScript, missing translations are automatically detected and reported as errors.

    Installation

    bash
    npm install intlayer i18next next-i18next i18next-resources-to-backend

    Configuring Intlayer to Export i18next Dictionaries

    Exporting i18next resources does not ensure 1:1 compatibility with other frameworks. It's recommended to stick to an Intlayer-based configuration to minimize issues.

    To export i18next resources, configure Intlayer in a intlayer.config.ts file. Example configurations:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],    defaultLocale: Locales.ENGLISH,  },  content: {    dictionaryOutput: ["i18next"],    i18nextResourcesDir: "./i18next/resources",  },};export default config;

    Here’s the continuation and correction of the remaining parts of your document:


    Importing Dictionaries into Your i18next Configuration

    To import the generated resources into your i18next configuration, use i18next-resources-to-backend. Below are examples:

    i18n/client.ts
    import i18next from "i18next";import resourcesToBackend from "i18next-resources-to-backend";i18next.use(  resourcesToBackend(    (language: string, namespace: string) =>      import(`../i18next/resources/${language}/${namespace}.json`)  ));

    Content Declaration

    Examples of content declaration files in various formats:

    **/*.content.ts
    import { t, type DeclarationContent } from "intlayer";const content = {  key: "my-content",  content: {    myTranslatedContent: t({      en: "Hello World",      fr: "Bonjour le monde",      es: "Hola Mundo",    }),  },} satisfies DeclarationContent;export default content;

    Build the next-i18next Resources

    To build the next-i18next resources, run the following command:

    bash
    npx run intlayer build

    This will generate resources in the ./i18next/resources directory. The expected output:

    bash
    .└── i18next    └── resources       └── en           └── my-content.json       └── fr           └── my-content.json       └── es           └── my-content.json

    Note: The i18next namespace corresponds to the Intlayer declaration key.

    Implement Next.js Plugin

    Once configured, implement the Next.js plugin to rebuild your i18next resources whenever Intlayer content declaration files are updated.

    next.config.mjs
    import { withIntlayer } from "next-intlayer/server";/** @type {import('next').NextConfig} */const nextConfig = {};export default withIntlayer(nextConfig);

    Using Content in Next.js Components

    After implementing the Next.js plugin, you can use the content in your components:

    src/components/myComponent/index.tsx
    import type { FC } from "react";import { useTranslation } from "react-i18next";const IndexPage: FC = () => {  const { t } = useTranslation();  return (    <div>      <h1>{t("my-content.title")}</h1>      <p>{t("my-content.description")}</p>    </div>  );};export default IndexPage;

    If you have an idea for improving this blog, please feel free to contribute by submitting a pull request on GitHub.

    GitHub link to the blog