O que voce vai aprender neste tutorial
✓ Roteamento i18n
✓ Gerenciamento de arquivos de traducao
✓ Configuracao do next-intl
✓ Troca dinamica de idioma
✓ Otimizacao para SEO
Step 1: Configuracao
npm install next-intl
Step 2: Arquivos de Traducao
// messages/ja.json
{
"home": {
"title": "Pagina Inicial",
"welcome": "Bem-vindo, {name}"
},
"nav": {
"home": "Inicio",
"about": "Sobre",
"contact": "Contato"
}
}
// 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({
// Outras configuracoes
});
Step 4: Configuracao i18n
// i18n.ts
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`./messages/${locale}.json`)).default
}));
Step 5: Middleware
// middleware.ts
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
locales: ['ja', 'en'],
defaultLocale: 'ja'
});
export const config = {
matcher: ['/((?!api|_next|.*\\..*).*)']
};
Step 6: Layout
// 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: Usando Traducoes
// 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: Seletor de Idioma
'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">Japones</option>
<option value="en">English</option>
</select>
);
}
Otimizacao para 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',
},
},
};
}
Resumo
Com next-intl, voce pode facilmente adicionar suporte multilingue ao seu app Next.js. Configure o roteamento e SEO adequadamente.
← Voltar para a lista