このチュートリアルで学ぶこと
✓ i18nルーティング
✓ 翻訳ファイル管理
✓ next-intl設定
✓ 動的ロケール切替
✓ SEO対応
Step 1: セットアップ
npm install next-intl
Step 2: 翻訳ファイル
// messages/ja.json
{
"home": {
"title": "ホームページ",
"welcome": "ようこそ、{name}さん"
},
"nav": {
"home": "ホーム",
"about": "会社概要",
"contact": "お問い合わせ"
}
}
// messages/en.json
{
"home": {
"title": "Home Page",
"welcome": "Welcome, {name}"
},
"nav": {
"home": "Home",
"about": "About",
"contact": "Contact"
}
}
Step 3: next.config.js
const withNextIntl = require('next-intl/plugin')();
module.exports = withNextIntl({
// 他の設定
});
Step 4: i18n設定
// i18n.ts
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`./messages/${locale}.json`)).default
}));
Step 5: ミドルウェア
// middleware.ts
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
locales: ['ja', 'en'],
defaultLocale: 'ja'
});
export const config = {
matcher: ['/((?!api|_next|.*\\..*).*)']
};
Step 6: レイアウト
// app/[locale]/layout.tsx
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
export default async function LocaleLayout({
children,
params: { locale }
}: {
children: React.ReactNode;
params: { locale: string };
}) {
const messages = await getMessages();
return (
<html lang={locale}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
Step 7: 翻訳の使用
// app/[locale]/page.tsx
import { useTranslations } from 'next-intl';
export default function HomePage() {
const t = useTranslations('home');
return (
<div>
<h1>{t('title')}</h1>
<p>{t('welcome', { name: 'Alice' })}</p>
</div>
);
}
Step 8: ロケール切替
'use client';
import { useLocale } from 'next-intl';
import { useRouter, usePathname } from 'next/navigation';
export function LocaleSwitcher() {
const locale = useLocale();
const router = useRouter();
const pathname = usePathname();
const switchLocale = (newLocale: string) => {
const newPath = pathname.replace(`/${locale}`, `/${newLocale}`);
router.push(newPath);
};
return (
<select value={locale} onChange={(e) => switchLocale(e.target.value)}>
<option value="ja">日本語</option>
<option value="en">English</option>
</select>
);
}
SEO対応
// app/[locale]/page.tsx
export async function generateMetadata({ params: { locale } }) {
const t = await getTranslations({ locale, namespace: 'home' });
return {
title: t('title'),
alternates: {
languages: {
ja: '/ja',
en: '/en',
},
},
};
}
まとめ
next-intlでNext.jsアプリを簡単に多言語対応できます。ルーティングとSEOも適切に設定しましょう。
← 一覧に戻る