next-intl 4
このスキルは、https://next-intl.dev/docs/getting-started に記載されている next-intl 4.x(ドキュメントバージョン 4.14.9 時点)をカバーします。習慣とは異なる点、つまり意外なデフォルト、落とし穴、レガシー API、そしてドキュメントが推奨するパターンをまとめています。リファレンスファイル内の各主張は、その出典元のページで締めくくられています。
ナビゲーション方法
- 以下のクイックスタートとクイックルールを読んでください。最も頻繁に発生する間違いをキャッチできます。
- 最後のテーブルから、タスクに一致するリファレンスファイルを1つ開いてください。
- コードで
setRequestLocale、requestLocale、またはmiddleware.tsを使用している場合は、最初に「古いパターン」のテーブルを読んでください。
クイックスタート(App Router)
App Router が推奨されるパスです。Pages Router は引き続きサポートされています。references/setup.md を参照してください。 https://next-intl.dev/docs/getting-started/pages-router
// next.config.ts
import {NextConfig} from 'next';
import createNextIntlPlugin from 'next-intl/plugin';
const nextConfig: NextConfig = {};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);
https://next-intl.dev/docs/getting-started/app-router
ロケールベースのURLを使用しない場合、src/i18n/request.ts はユーザーのプリファレンス、最もシンプルな場合はクッキーからロケールを解決します。
// src/i18n/request.ts
import {cookies} from 'next/headers';
import {getRequestConfig} from 'next-intl/server';
export default getRequestConfig(async () => {
const store = await cookies();
const locale = store.get('locale')?.value || 'en';
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default
};
});
https://next-intl.dev/docs/getting-started/app-router
// src/app/layout.tsx
import {NextIntlClientProvider} from 'next-intl';
import {getLocale} from 'next-intl/server';
export default async function RootLayout({children}) {
const locale = await getLocale();
return (
<html lang={locale}>
<body>
<NextIntlClientProvider>{children}</NextIntlClientProvider>
</body>
</html>
);
}
https://next-intl.dev/docs/getting-started/app-router 、 https://next-intl.dev/docs/usage/configuration
import {useTranslations} from 'next-intl';
import {getTranslations} from 'next-intl/server';
export function HomePage() {
const t = useTranslations('HomePage'); // 非asyncコンポーネント
return <h1>{t('title')}</h1>;
}
export async function Profile() {
const t = await getTranslations('ProfilePage'); // asyncコンポーネント
return <h1>{t('title')}</h1>;
}
https://next-intl.dev/docs/getting-started/app-router
/en/about 形式のURLを使用する場合は、src/i18n/routing.ts、src/proxy.ts、src/i18n/navigation.ts を追加し、トップレベルの [locale] セグメントを追加します: references/routing.md。 https://next-intl.dev/docs/routing/setup
クイックルール
セットアップ
- プラグインは
src/またはプロジェクトルート内のi18n/request.ts(.ts、.tsx、.js、.jsx)を見つけます。それ以外の場所にある場合は、パスを渡します:createNextIntlPlugin('./somewhere/else/request.ts')。 https://next-intl.dev/docs/getting-started/app-router - ドキュメントの例では
const locale = 'en'がハードコードされています。実際の解決(クッキー、ユーザー設定、またはnext/root-params)に置き換えてください。 https://next-intl.dev/docs/getting-started/app-router getRequestConfigはリクエストごとに、サーバーコンポーネントのレンダーパスで1回実行されるため、cookies()とheaders()はそこで使用できます。 https://next-intl.dev/docs/usage/configuration- リクエスト設定で
timeZoneを設定してください。デフォルトはサーバーランタイムのタイムゾーンです。 https://next-intl.dev/docs/usage/configuration
ルーティング
- Next.js 16 ではファイル名を
src/proxy.tsにしてください。インポートはnext-intl/middlewareからのcreateMiddlewareのままです。 https://next-intl.dev/docs/routing/setup next/root-paramsからのawait rootParams.locale()でロケールを読み取り、hasLocale(routing.locales, value)で検証し、それ以外の場合はnotFound()を呼び出します。16.3 より前の Next.js ではexperimental.rootParamsが必要です。 https://next-intl.dev/docs/routing/setupLink、redirect、usePathname、useRouter、getPathnameは、next/linkやnext/navigationではなく、自身のi18n/navigation.tsからインポートしてください。 https://next-intl.dev/docs/routing/navigation- ロケールを切り替えるには、そのモジュールから
router.replace(pathname, {locale})を使用します。<Link locale>はプリフェッチされず、ロケールクッキーの上書きを防ぎます。 https://next-intl.dev/docs/routing/navigation redirectは常にロケールを取得します:redirect({href: '/login', locale})。TypeScript が型を絞り込めるように、return redirect(...)と記述してください。 https://next-intl.dev/docs/routing/navigation- デフォルトのマッチャーはドットを含むパスをスキップします。
/users/jane.doeのようなルートには明示的なエントリを追加してください。 https://next-intl.dev/docs/routing/middleware
クライアントコンポーネント
messagesプロパティのないNextIntlClientProviderは、すべてのメッセージをクライアントに送信します。メッセージを制限するには、messages={pick(messages, 'Namespace')}またはmessages={null}を渡してください。 https://next-intl.dev/docs/environments/server-client-components- サーバーコンポーネントで翻訳し、ラベルを props または
childrenとしてクライアントコンポーネントに渡すことを推奨します。 https://next-intl.dev/docs/environments/server-client-components onErrorとgetMessageFallbackはサーバーコンポーネントから渡すことができません。これらは、サーバープロバイダー内にネストした独自の'use client'プロバイダーで設定してください。このプロバイダーはロケールとメッセージを継承するため、これらを手動で渡す必要はありません。 https://next-intl.dev/docs/usage/configuration
メッセージ
- キーと名前空間に
.を含めることはできません。これはネストを意味します。ネストされた JSON のみを使用してください。 https://next-intl.dev/docs/usage/translations - ICU の引数名と
selectの値は、英字、数字、_のみ使用可能で、ダッシュは使用できません。en-GBはen_GBにマッピングしてください。selectにはotherケースが必要です。 https://next-intl.dev/docs/usage/translations - 自己終了タグはメッセージ内で終了タグが必要です:
<br></br>。 https://next-intl.dev/docs/usage/translations - サーバーアクション、メタデータ、ルートハンドラーでは、ロケールが推論されない可能性があるため、
getTranslations({locale, namespace})を使用してください。 https://next-intl.dev/docs/environments/actions-metadata-route-handlers
テスト
- Vitest と
createNavigationを使用する場合:server.deps.inline: ['next-intl']。Jest の場合:transformIgnorePatterns: ['node_modules/(?!next-intl)/']。next-intl は ESM のみです。 https://next-intl.dev/docs/environments/testing
古いパターン
| 古いパターン | 現在のパターン |
|---|---|
src/middleware.ts | src/proxy.ts(Next.js 16 の場合)、同じ createMiddleware コード |
すべてのレイアウトとページの先頭にある setRequestLocale(locale) | i18n/request.ts 内の next/root-params、静的レンダリングは不要に |
getRequestConfig(async ({requestLocale}) => ...) | getRequestConfig(async ({locale}) => ...)、rootParams.locale() のフォールバック付き |
フラットなメッセージキー "HomePage.title" | ネストされたオブジェクト {"HomePage": {"title": ...}} |
dangerouslySetInnerHTML 内の HTML を使用した t.raw | t.rich(React)または t.markup(文字列)、t.raw は解析をスキップしサニタイズされる場合のみ |
詳細:references/routing.md および references/messages.md。
リファレンスファイル
| ファイル | 内容 |
|---|---|
| references/setup.md | プラグイン、リクエスト設定、プロバイダーのデフォルト、ルーティングなしのロケール、メッセージストレージ、Pages Router |
| references/routing.md | defineRouting、[locale] セグメント、proxy.ts、マッチャー、next/root-params、静的レンダリング、localePrefix、ドメイン、クッキー、代替リンク、ローカライズされたパス名、静的エクスポート、トラブルシューティング |
| references/navigation.md | createNavigation、Link、useRouter、usePathname、redirect、getPathname、ロケールスイッチャー、型付けされた href |
| references/messages.md | useTranslations、名前空間、ICU 複数形と選択、リッチテキスト、t.markup、t.raw、t.has、配列、欠落メッセージ、onError、タイムゾーン、now |
| references/formatting.md | useFormatter:日付、相対時間、範囲、数値、リスト、表示名、ICU スケルトン、グローバル書式 |
| references/server-and-client.md | サーバーコンポーネントとクライアントコンポーネント、メッセージの選択、メタデータ、サーバーアクション、Zod、ルートハンドラー、サイトマップ、OG 画像、404 とエラーファイル |
| references/extraction.md | 実験的な useExtracted と getExtracted、プラグインの experimental オプション、PO ファイル、プリコンパイル、カスタムコーデック、モノレポ |
| references/typescript-and-tooling.md | AppConfig の拡張、型安全な引数、Jest と Vitest を使ったテスト、Storybook、use-intl コア、ランタイム要件、リンティング、翻訳管理、エージェント規約 |
クロール済みページ:SOURCES.md。