bash Copy code
# Step 1: Create a new Next.js project
npx create-next-app@latest my-i18n-app --typescript --tailwind --eslint --app --src-dir --import-alias="@/*"
cd my-i18n-app
# Step 2: Install next-intl
npm install next-intl
# Step 3: Replace/create the files as shown below
Project Structure
code Copy code
my-i18n-app/
├── src/
│ ├── app/
│ │ ├── [locale]/
│ │ │ ├── layout.tsx
│ │ │ └── page.tsx
│ │ ├── globals.css
│ │ └── layout.tsx
│ ├── components/
│ │ └── LanguageSwitcher.tsx
│ └── messages/
│ ├── en.json
│ └── es.json
├── i18n.ts
├── middleware.ts
├── next.config.js
├── package.json
└── tsconfig.json (default)
File Contents
i18n.ts (root)
ts Copy code
import {getRequestConfig} from 'next-intl/server';
export default getRequestConfig(async ({locale}) => ({
messages: (await import(`./src/messages/${locale}.json`)).default
}));
middleware.ts (root)
ts Copy code
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
// A list of all locales that are supported
locales: ['en', 'es'],
// If this locale is matched, pathnames work without a prefix (e.g. `/about`)
defaultLocale: 'en'
});
export const config = {
// Skip all paths that should not be internationalized. This example skips the
// folders "api", "_next" and all files with an extension (e.g. favicon.ico)
matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
};
next.config.js (root)
js Copy code
/** @type {import('next').NextConfig} */
const createNextIntlPlugin = require('next-intl/plugin');
const withNextIntl = createNextIntlPlugin();
module.exports = withNextIntl({
// Other Next.js config...
});
src/app/layout.tsx
tsx Copy code
import type {Metadata} from 'next';
import {Inter} from 'next/font/google';
import './globals.css';
import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';
const inter = Inter({subsets: ['latin']});
export const metadata: Metadata = {
title: 'Next.js i18n App',
description: 'Next.js app with internationalization and dynamic language switching',
};
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const messages = await getMessages();
return (
<html lang={messages.IntlMessageFormat.__locale__}>
<body className={inter.className}>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
src/app/[locale]/layout.tsx
tsx Copy code
import {LanguageSwitcher} from '@/components/LanguageSwitcher';
export default function LocaleLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
<header className="bg-white shadow-sm border-b">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<h1 className="text-2xl font-bold text-gray-900">🌍 i18n App</h1>
<LanguageSwitcher />
</div>
</div>
</header>
<main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
{children}
</main>
</div>
);
}
src/app/[locale]/page.tsx
tsx Copy code
import {useTranslations} from 'next-intl';
export default function Home() {
const t = useTranslations('Home'); // Namespace for organization
return (
<div className="text-center">
<h2 className="text-5xl font-extrabold text-gray-900 mb-8 bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
{t('title')}
</h2>
<p className="text-xl text-gray-700 mb-12 max-w-2xl mx-auto leading-relaxed">
{t('description')}
</p>
<div className="space-y-4">
<button className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg text-lg transition-colors duration-200 shadow-lg hover:shadow-xl">
{t('cta')}
</button>
<p className="text-sm text-gray-500">{t('footer')}</p>
</div>
</div>
);
}
src/components/LanguageSwitcher.tsx
tsx Copy code
'use client';
import {useRouter, usePathname} from 'next/navigation';
import {useLocale, useTranslations} from 'next-intl';
export function LanguageSwitcher() {
const router = useRouter();
const pathname = usePathname();
const locale = useLocale();
const t = useTranslations('LanguageSwitcher');
const otherLocales = {
en: 'es',
es: 'en'
};
function onSelectChange(newLocale: string) {
router.push(pathname.replace(`/${locale}`, `/${newLocale}`));
}
return (
<div className="flex items-center space-x-2">
<label htmlFor="locale" className="text-sm font-medium text-gray-700">
{t('label')}
</label>
<select
id="locale"
className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md shadow-sm bg-white"
defaultValue={locale}
onChange={(e) => onSelectChange(e.target.value)}
>
<option value="en">🇺🇸 English</option>
<option value="es">🇪🇸 Español</option>
</select>
</div>
);
}
src/messages/en.json
json Copy code
{
"Home": {
"title": "Welcome to the Future of Web Apps!",
"description": "This is a fully internationalized Next.js app with dynamic language switching. Change the language above and see the magic happen without a page reload.",
"cta": "Get Started Now",
"footer": "Powered by Next.js 14 & next-intl 🚀"
},
"LanguageSwitcher": {
"label": "Language:"
}
}
src/messages/es.json
json Copy code
{
"Home": {
"title": "¡Bienvenido al Futuro de las Apps Web!",
"description": "Esta es una app Next.js completamente internacionalizada con cambio dinámico de idioma. Cambia el idioma arriba y observa la magia sin recargar la página.",
"cta": "¡Comenzar Ahora!",
"footer": "Desarrollado con Next.js 14 & next-intl 🚀"
},
"LanguageSwitcher": {
"label": "Idioma:"
}
}
src/app/globals.css (update to include Tailwind directives if not already)
css Copy code
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 4: Run the App
Open http://localhost:3000
Default: /en (English)
Switch to Spanish: Select "Español" → navigates to /es instantly.
Fully client-side switching with smooth transitions.
Translations update dynamically.
SEO-friendly with locale-prefixed routes.
Features
Internationalized Routing : /en, /es paths.
Dynamic Switching : Client-side via useRouter + usePathname, no full reload.
TypeScript : Full support.
Tailwind CSS : Styled with modern design.
Scalable : Add more locales/translations easily.
Server/Client Components : Proper hybrid rendering.
This is a production-ready starter! Extend with more pages, namespaces, or formats (ICU messages). See next-intl docs for advanced features.