プログラミング

【Next.js】app routerでの多言語対応

概要

Next.jsにて多言語対応をしようと考えている方に向けて、簡単な構築方法を書き溜めた記事となります。
これからNext.jsで実装しようとしている方&将来的にNext.jsのバージョンを13以上に上げようと考えてる方は、本記事が助けになればいいと思います。

ちなみに本記事で使用しているNext.jsのバージョンは14.2.7になります。

つくってみよう!

まずはNext.jsで多言語対応を行う為、「i18next」と「next-i18n-router」パッケージをインストールします。

yarn add i18next next-i18n-router

その後、srcフォルダの下にi18nフォルダを作成し、以下各ファイルを作成します。
下記config.tsファイルで設定していますが、今回英語(en)をデフォルト言語として設定しています。

i18n/config.ts

import i18n, { InitOptions } from "i18next";
import { en } from "./langs/en";
import { ja } from "./langs/ja";

export const initI18n = () => {
  i18n.init(i18nextInitOptions, (err) => {
    if (err) {
      console.error("i18next failed to initialize", err);
    }
  });

  return i18n;
};

export const i18nConfig = {
  locales: ["en", "ja"],
  defaultLocale: "en",
};

export const i18nextInitOptions: InitOptions = {
  lng: "en",
  fallbackLng: "en",
  resources: {
    en,
    ja,
  },
};

i18n/langs/en.ts

export const en = {
  translation: {
    hello: "Hello",
  },
};

i18n/langs/ja.ts

export const ja = {
  translation: {
    hello: "こんにちは",
  },
};

またsrcフォルダの下にmiddleware.tsファイルも作成します。

src/middleware.ts

import { i18nConfig } from "@/i18n/config";
import { i18nRouter } from "next-i18n-router";
import { NextRequest } from "next/server";

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).*)",
};

これで、英語と日本語の多言語対応を行う準備がととのいました。

画面側をつくってみよう!

次に画面側です。app routerのフォルダ構造はsrc/app/[lang]/page.tsxのような形になります。

src/app/[lang]/page.tsx

import { initI18n } from "@/i18n/config";
import { t } from "i18next";

const i18n = initI18n();
export default function Page({
  params: { lang },
}: {
  params: {
    lang: string;
  };
}) {
  i18n.changeLanguage(lang);
  const hello = t("hello");
  console.log(hello);
  return (
    <body>
      <h1>{hello}</h1>
    </body>
  );
}

上記画面が作れたら、Next.jsを起動してみましょう!しかし、http://localhost:3000に遷移すると、お使いのブラウザの言語設定が日本語であればhttp://localhost:3000/jaに自動遷移されるかと思います。英語設定に移りたい場合はhttp://localhost:3000/enと入力しましょう!

以下日本語、英語の各画面の様子です。

これで多言語対応を簡単に実装することができましたね!
他に幾つか多言語対応できるパッケージがありますが、なるべく簡易に、かつ管理しやすい形で多言語設定したい場合は本実装がベターな気がしてます。

参考

next-i18n-router
i18next

スポンサーリンク

  • この記事を書いた人

かず

バックエンド/フロントエンド/クラウドインフラのフルスタックエンジニア | デジタルノマド(‘23/6〜) で世界放浪中 | 主にプログラミングに役立つ情報を発信 | Xでは旅の様子を発信

-プログラミング
-,