🌏
Next.js15のAppルーターでi18n対応するためのテンプレート
細かいことはいいから早く開発を始めたい、という方はこちらのリポジトリをフォークしてください。
手元に環境を構築したい場合
Next.js15系環境を作成
npx create-next-app YOUR_PROJECT_NAME --typescript
Need to install the following packages:
create-next-app@15.1.7
Ok to proceed? (y) y
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes
i18nパッケージのインストール
npm install i18next i18next-resources-to-backend next-i18n-router react-i18next
i18nConfig.ts
を作成
ルートフォルダにtouch ./i18nConfig.ts
// ./i18nConfig.ts
export const i18nConfig = {
locales: ['en', 'ja'] as const,
defaultLocale: 'en', // Dafault locale
};
middleware.ts
を作成
srcフォルダ下に touch ./src/middleware.ts
// ./src/middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { i18nRouter } from 'next-i18n-router';
import { i18nConfig } from '../i18nConfig';
export function middleware(request: NextRequest): NextResponse {
return i18nRouter(request, i18nConfig);
}
// このmiddlewareを適用する範囲を指定
export const config = {
matcher: '/((?!api|static|.*\\..*|_next).*)',
};
i18n.ts
を作成
src/appフォルダ下に touch ./src/app/i18n.ts
// src/app/i18n.ts
import { createInstance, i18n, Resource } from 'i18next';
import { initReactI18next } from 'react-i18next/initReactI18next';
import resourcesToBackend from 'i18next-resources-to-backend';
import { i18nConfig } from '../../i18nConfig';
type InitTranslationsParams = {
locale: string; // 現在のロケール
namespaces: string[]; // ロードしたい名前空間
i18nInstance?: i18n; // すでに生成済みの i18n インスタンス (クライアント用)
resources?: Resource; // 既にサーバーから受け取った翻訳リソース
};
export async function initTranslations({
locale,
namespaces,
i18nInstance,
resources,
}: InitTranslationsParams) {
// 既存インスタンスがなければ作成
const instance = i18nInstance || createInstance();
// i18next に react-i18next を組み込む
instance.use(initReactI18next);
// サーバー側でJSONを動的読み込みするための設定
if (!resources) {
instance.use(
resourcesToBackend((language: string, namespace: string) =>
import(`@/locales/${language}/${namespace}.json`)
)
);
}
// i18n初期化
if (!instance.isInitialized) {
await instance.init({
lng: locale,
resources,
fallbackLng: i18nConfig.defaultLocale,
supportedLngs: i18nConfig.locales as unknown as string[],
defaultNS: namespaces[0],
fallbackNS: namespaces[0],
ns: namespaces,
preload: resources ? [] : i18nConfig.locales, // サーバープリロード
});
} else {
// 既に初期化済みの場合、言語を更新するだけでもOK
instance.changeLanguage(locale);
}
return {
i18n: instance,
// 全部の翻訳リソース (クライアントへ渡すときに使う)
resources: instance.services.resourceStore.data,
t: instance.t,
};
}
src/app下に[locale]フォルダを作成し、TSXファイルを移動
mkdir ./src/app/[locale]
mv ./src/app/page.tsx ./src/app/[locale]/
mv ./src/app/layout.tsx ./src/app/[locale]/
layout.tsxのcssインポートのインポートパスを修正
srcフォルダ以下にlocalesフォルダを作成し、enフォルダとjaフォルダを作成
mkdir ./src/locales
mkdir ./src/locales/en && mkdir ./src/locales/ja
src/locales/enフォルダとsrc/locales/jaフォルダ以下にそれぞれcommon.jsonを作成
touch ./src/locales/en/common.json
touch ./src/locales/ja/common.json
TranslationsProvider.tsxを作成
どのフォルダでもいいのでTranslationsProvider.tsx
を作成
touch ./src/TranslationsProvider.tsx
// components/TranslationsProvider.tsx
'use client';
import { ReactNode } from 'react';
import { I18nextProvider } from 'react-i18next';
import { initTranslations } from '@/app/i18n';
import { createInstance, i18n, Resource } from 'i18next';
interface TranslationsProviderProps {
children: ReactNode;
locale: string;
namespaces: string[];
resources: Resource;
}
export default function TranslationsProvider({
children,
locale,
namespaces,
resources,
}: TranslationsProviderProps) {
// クライアント側で新たに i18n インスタンスを作成
const i18nClient: i18n = createInstance();
// initTranslations を呼んでクライアントでも初期化
// (サーバーから受け取った resources を使うことで無駄なリソース取得を回避)
initTranslations({
locale,
namespaces,
i18nInstance: i18nClient,
resources,
});
return <I18nextProvider i18n={i18nClient}>{children}</I18nextProvider>;
}
サーバーコンポーネントを多言語化する
initTranslations のインポートと locale の取得
Next.js15から属性の取得が非同期化しました。
const { locale } = await props.params;
[サンプル] page.tsx
import Image from "next/image";
import SampleClientComponents from "@/components/SampleClientComponents";
import { initTranslations } from "@/app/i18n";
interface TranslationsProviderProps {
params: {
locale: string;
};
}
export default async function Home(props: TranslationsProviderProps) {
const { locale } = await props.params;
const { t } = await initTranslations({
locale,
namespaces: ["common"],
});
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
{`${t("get_started_by_editing")}`}{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
src/app/page.tsx
</code>
.
</li>
<li className="mb-2">{`${t("save_and_see_your_changes_instantly")}.`}</li>
<li className="mb-2">{`Current Locale is ${locale}.`}</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
{`${t("deploy_now")}`}
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
{`${t("read_our_docs")}`}
</a>
</div>
<SampleClientComponents />
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org →
</a>
</footer>
</div>
);
}
クライアントコンポーネントを多言語化する
プロバイダーを作成する。
どこでもいいのでTranslationsProvider.tsxを作成。(src/componentsに作成)
// components/TranslationsProvider.tsx
'use client';
import { ReactNode } from 'react';
import { I18nextProvider } from 'react-i18next';
import { initTranslations } from '@/app/i18n';
import { createInstance, i18n, Resource } from 'i18next';
interface TranslationsProviderProps {
children: ReactNode;
locale: string;
namespaces: string[];
resources: Resource;
}
export default function TranslationsProvider({
children,
locale,
namespaces,
resources,
}: TranslationsProviderProps) {
// クライアント側で新たに i18n インスタンスを作成
const i18nClient: i18n = createInstance();
// initTranslations を呼んでクライアントでも初期化
initTranslations({
locale,
namespaces,
i18nInstance: i18nClient,
resources,
});
return <I18nextProvider i18n={i18nClient}>{children}</I18nextProvider>;
}
layout.tsxにプロバイダーを追加。
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
// import "./globals.css";
import "../globals.css";
import { initTranslations } from "@/app/i18n";
import TranslationsProvider from "@/components/TranslationsProvider";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default async function RootLayout({
children,
params,
}: Readonly<{
children: React.ReactNode;
params: { locale: string };
}>) {
const { locale } = await params;
const namespaces = ["common"];
const { resources } = await initTranslations({
locale,
namespaces: namespaces,
});
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<TranslationsProvider locale={locale} namespaces={namespaces} resources={resources}>
{children}
</TranslationsProvider>
</body>
</html>
);
}
クライアントコンポーネント側でuseTranslationを使用しリソースを取得
'use client'
import React from 'react';
import { useTranslation } from 'react-i18next';
export default function SampleClientComponents() {
const { t } = useTranslation("common");
return (
<div className="p-3 rounded-xl flex items-center justify-center w-full bg-gradient-to-br from-gray-900 via-gray-800 to-black text-white">
{t("this_is_a_sample_client_component")}
</div>
);
}
これでひとまず完了です。
Discussion