iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐡

Internationalization in Next.js App Router with next-i18n-router

に公開
2024/04/03
2件

next-i18n-router and i18next are used to handle i18n cleanly. Additionally, CSR support is provided by react-i18next.
A sample (GitHub) is available.

next-i18n-router Configuration

First, follow the instructions in the next-i18n-router README (mostly translated here).

  • Package install

      npm install next-i18n-router
    
  • Create the config

    export const i18nConfig = {
      locales: ["en", "ja"],
      defaultLocale: "ja",
    };
    
  • Move all files under app to the [locale] directory

      └── app
        └── [locale]
            ├── layout.js
            └── page.js
    
  • Add middleware

    import { i18nRouter } from "next-i18n-router";
    import { NextRequest } from "next/server";
    import { i18nConfig } from "@/i18n/config";
    
    export function middleware(request: NextRequest) {
      return i18nRouter(request, i18nConfig);
    }
    
    // only applies this middleware to files in the app directory
    export const config = {
      matcher: "/((?!api|static|.*\\..*|_next).*)",
    };
    
  • With these settings, you can now obtain the locale according to the browser's language settings in both client-side and server-side as follows:

    'use client';
    
    import { useCurrentLocale } from 'next-i18n-router/client';
    import i18nConfig from '@/i18nConfig';
    
    function ExampleClientComponent() {
      const locale = useCurrentLocale(i18nConfig);
    
      ...
    }
    
      // server component
    function ExampleServerComponent({ params: { locale } }) {
      ...
    }
    

Furthermore, if the default locale is set to ja, the locale path will be omitted when the browser's language setting is Japanese. For example, for routing to products, the paths would be:

Japanese: /products
English: /en/products

Multi-language Support for Server Components with i18next

We will now integrate i18next to support SSG-rendered components.

  • Package install

    npm install i18next
    
  • Add the i18next language settings.

    import { InitOptions } from "i18next";
    import { en } from "./en";
    import { ja } from "./ja";
    
    export const i18nextInitOptions: InitOptions = {
      lng: "ja",
      fallbackLng: "ja",
      resources: {
        en,
        ja,
      },
    };
    
    export const ja = {
      translation: {
        hello: "こんにちは!",
      },
    };
    
    export const en = {
      translation: {
        hello: "Hello!",
      },
    };
    
  • Using the established language settings, initialize the i18n instance and configure the language in layout.tsx.

    import i18n from "i18next";
    import { i18nextInitOptions } from "@/i18n/config";
    
    i18n.init(i18nextInitOptions, (err) => {
      if (err) {
        console.error("i18next failed to initialize", err);
      }
    });
    
    export default function RootLayout({
      children,
      params: { locale },
    }: {
      children: React.ReactNode;
      params: {
        locale: string;
      };
    }) {
      i18n.changeLanguage(locale);
      return (
        <html lang={locale}>
          <body>{children}</body>
        </html>
      );
    }
    
  • With this, you can now use the t function in Server Components according to the client's language settings.

    import { t } from "i18next";
    
    export default function Hello() {
      return <p>{t("hello")}</p>; // "こんにちは!" (Hello!) if Japanese, "Hello!" if English
    }
    

Client Component Support with react-i18next

While keeping the same i18next configuration file, we will enable the t function for CSR (Client-Side Rendering) as well.

  • Package install

    npm install react-i18next
    
  • Create a Provider. Although we will add this to layout.tsx, I18nextProvider needs to be prepared as a client component because it handles client-side state (meaning "use client" is required).

    "use client";
    import i18n from "i18next";
    import { i18nConfig, i18nextInitOptions } from "@/i18n/config";
    import { I18nextProvider } from "react-i18next";
    import { useCurrentLocale } from "next-i18n-router/client";
    import { ReactNode } from "react";
    
    i18n.init(i18nextInitOptions, (err) => {
      if (err) {
        console.error("i18next failed to initialize", err);
      }
    });
    
    export const I18nProvider = ({ children }: { children: ReactNode }) => {
      i18n.changeLanguage(useCurrentLocale(i18nConfig));
      return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>;
    };
    
  • Add it to layout.tsx.

    import i18n from "i18next";
    import { i18nextInitOptions } from "@/i18n/config";
    import { I18nProvider } from "./i18nProvider";
    
    export const metadata = {
      title: "Next.js",
      description: "Generated by Next.js",
    };
    
    i18n.init(i18nextInitOptions, (err) => {
      if (err) {
        console.error("i18next failed to initialize", err);
      }
    });
    
    export default function RootLayout({
      children,
      params: { locale },
    }: {
      children: React.ReactNode;
      params: {
        locale: string;
      };
    }) {
      i18n.changeLanguage(locale);
      return (
        <html lang={locale}>
          <body>
            <I18nProvider>{children}</I18nProvider>
          </body>
        </html>
      );
    }
    
  • Now, you can handle multi-language support in Client Components in the same way as Server Components.

    "use client";
    import { t } from "i18next";
    
    export default function Hello() {
      return <p>{t("hello")}</p>; // "こんにちは!" if Japanese, "Hello!" if English
    }
    

Impressions

Initially, I implemented it following the Next.js documentation, but it felt a bit cumbersome. Using next-i18n-router made the setup much cleaner.

Regarding Server Components support, it feels like it might be possible to set things up in the middleware if we could manage the i18n instance with NextRequest, but I couldn't get it to work well, so I settled on the current approach of writing it in layout.tsx. (If you know of a better way, please let me know in the comments!)

GitHubで編集を提案

Discussion

打田裕馬打田裕馬

参考リポジトリまで付けていただき、非常に助かりました!
ありがとうございます👏

1
ちびはむちびはむ

力になれたようで嬉いです!🐟
コメントまでいただきありがとうございます!

1