Lo que Aprenderas en este Tutorial
✓ Enrutamiento i18n
✓ Gestion de archivos de traduccion
✓ Configuracion de next-intl
✓ Cambio dinamico de idioma
✓ Soporte SEO
Step 1: Configuracion
npm install next-intl
Step 2: Archivos de Traduccion
// messages/ja.json
{
"home": {
"title": "Pagina Principal",
"welcome": "Bienvenido, {name}"
},
"nav": {
"home": "Inicio",
"about": "Acerca de",
"contact": "Contacto"
}
}
// 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({
// Otras configuraciones
});
Step 4: Configuracion 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: Uso de Traducciones
// 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: Cambio 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>
);
}
Soporte 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',
},
},
};
}
Resumen
Con next-intl puedes agregar soporte multiidioma a tu aplicacion Next.js facilmente. Asegurate de configurar correctamente el enrutamiento y el SEO.
← Volver a la lista