The user wants a Next.js application with internationalization (i18n) and dynamic language switching.
Key Requirements:
- Framework: Next.js.
- Core Feature: Internationalization (i18n).
- Specific Functionality: Dynamic language switching (user can change languages without page refresh or with seamless navigation).
- Approach: There are two main ways to do i18n in Next.js:
- Built-in Routing (Legacy/Config based): Using
next.config.js i18n object. This handles sub-paths (/en/about, /fr/about) or subdomains. Note: This is removed in the App Router (Next.js 13+). Since modern Next.js is the standard, I should focus on the App Router approach or the popular next-i18next library for the Pages Router.
- App Router (Next.js 13+): Uses Middleware and directory-based routing (
[lang] folder). This is the current best practice.
- Library:
next-intl is the industry standard for both, but especially powerful in the App Router. react-i18next / next-i18next is good for the Pages Router.
Decision:
I will build this using Next.js 14+ (App Router) and the next-intl library. This is the most modern, performant, and recommended way to handle translations and routing in the current ecosystem.
Step-by-Step Plan:
- Setup: Initialize a Next.js app.
- Dependencies: Install
next-intl.
- Configuration:
- Create
i18n.ts config file.
- Create Middleware to handle locale detection and redirection.
- Directory Structure:
- Move
page.tsx inside a [locale] folder to handle dynamic routes.
- Create a
layout.tsx inside [locale].
- Translations:
- Create JSON files for messages (e.g.,
en.json, fr.json).
- Language Switcher:
- Create a component that allows the user to select a language.
- This needs to use the router to change the path segment.
- Implementation Details:
- Middleware: Detect browser headers, match against supported locales, redirect if necessary.
- Provider: Wrap the app in
NextIntlClientProvider.
- Server vs Client: Server components are preferred, but the switcher needs to be a client component.
Code Structure Draft:
src/i18n.ts (config)
src/middleware.ts (routing logic)
src/locales/en.json, src/locales/es.json
src/app/[locale]/layout.tsx (root layout with provider)
src/app/[locale]/page.tsx (home page)
src/components/LanguageSwitcher.tsx (client component for switching)
Refining the Solution:
- Next.js Version: 14.
- Config:
next-intl creates a "request context". In the App Router, we usually use getRequestConfig in i18n.ts.
- Middleware: Standard boilerplate from
next-intl docs.
- Switching: Simple links to
/en or /es.
Self-Correction/Edge Cases:
- Hydration Mismatches: Ensure the layout uses the
locale param correctly.
- Font optimization: Not strictly necessary for the example but good practice. I'll skip for brevity to focus on i18n.
- Client vs Server: Translations can be accessed in Server Components easily. The Switcher needs
useRouter or simple <Link> tags.
Let's write the code.
Phase 1: Install & Setup
npx create-next-app@latest my-app
npm install next-intl
Phase 2: File Structure
Need to explain the move to app/[locale].
Phase 3: Code Content
i18n/meta: createSharedPathnamesNavigation is a cool feature of next-intl to get typed routers.
middleware: Needs to export middleware and config.
Drafting the response:
- Prerequisites: Node.js installed.
- Step 1: Installation.
- Step 2: Configuration (i18n setup).
- Step 3: Middleware (Routing).
- Step 4: Folder Structure & Layout (The App Router setup).
- Step 5: Translations (JSON).
- Step 6: The Language Switcher Component.
- Step 7: The Main Page.
- Explanation of how it works.
This looks solid. I will provide a complete, copy-pasteable example using Next.js 14 (App Router) and next-intl.
Double check on next-intl versions:
Version 3.x is the current standard for App Router.
Configuration changed slightly from 2.x. I must ensure I use the v3 approach (creating i18n/request.ts or i18n.ts and the plugin in next.config.js).
Actually, for a simple tutorial, I don't strictly need the Babel plugin, but it's recommended for performance. I'll stick to the standard programmatic setup to keep it simpler for the user.
Let's construct the actual code blocks.
middleware.ts:
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
locales: ['en', 'fr', 'es'],
defaultLocale: 'en'
});
export const config = { matcher: ... };
i18n.ts:
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`./locales/${locale}.json`)).default
}));
next.config.mjs: needs createNextIntlPlugin.
app/[locale]/layout.tsx: Needs NextIntlClientProvider.
app/[locale]/page.tsx: Uses useTranslations.
This seems perfect. I will present this clearly.
This example uses Next.js 14+ (App Router) and next-intl, which is the industry standard for internationalization in modern Next.js applications.
Prerequisites
Initialize a new Next.js project:
npx create-next-app@latest my-i18n-app
# Select defaults: TypeScript=Yes, ESLint=Yes, Tailwind=Yes, App Router=Yes
cd my-i18n-app
Step 1: Install Dependencies
Install next-intl:
npm install next-intl
Step 2: Configuration
1. Create Translation Files
Create a folder structure for your messages.
messages/en.json
messages/fr.json
messages/es.json
// messages/en.json
{
"Index": {
"title": "Hello world",
"description": "This is a Next.js app with internationalization."
}
}
// messages/fr.json
{
"Index": {
"title": "Bonjour le monde",
"description": "Ceci est une application Next.js avec internationalisation."
}
}
2. Create the i18n config file
Create src/i18n.ts (or i18n.ts in root) to setup the request configuration.
// i18n.ts
import {getRequestConfig} from 'next-intl/server';
export default getRequestConfig(async ({locale}) => ({
messages: (await import(`./messages/${locale}.json`)).default
}));
3. Update next.config.mjs
Add the createNextIntlPlugin to your config.
// next.config.mjs
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNextIntl(nextConfig);
Step 3: Middleware & Routing
1. Setup Middleware
Create src/middleware.ts to detect the user's language and redirect them.
// middleware.ts
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
// A list of all locales that are supported
locales: ['en', 'fr', 'es'],
// Used when no locale matches
defaultLocale: 'en'
});
export const config = {
// Match only internationalized pathnames
matcher: ['/', '/(fr|en|es)/:path*']
};
2. Restructure the App Directory
Move your page.tsx inside a dynamic [locale] folder.
- Old:
app/page.tsx
- New:
app/[locale]/page.tsx
Step 4: The Layout & Root Setup
1. Generate Static Params
In app/[locale]/layout.tsx, you need to tell Next.js which languages to generate at build time.
// app/[locale]/layout.tsx
import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';
import {notFound} from 'next/navigation';
const locales = ['en', 'fr', 'es'];
export function generateStaticParams() {
return locales.map((locale) => ({locale}));
}
export default async function LocaleLayout({
children,
params: {locale}
}: {
children: React.ReactNode;
params: {locale: string};
}) {
// Validate locale
if (!locales.includes(locale)) {
notFound();
}
// Providing messages to the Client Components
const messages = await getMessages();
return (
<html lang={locale}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
Step 5: The Language Switcher Component
Create a client component to switch languages. We use usePathname and useRouter to replace the current URL prefix.
// components/LanguageSwitcher.tsx
'use client';
import { usePathname, useRouter } from 'next/navigation';
import { useState } from 'react';
const languages = [
{ code: 'en', name: 'English' },
{ code: 'fr', name: 'French' },
{ code: 'es', name: 'Spanish' },
];
export default function LanguageSwitcher() {
const router = useRouter();
const pathname = usePathname();
// Extract current language from URL (e.g., /en/about -> 'en')
const currentLocale = pathname.split('/')[1];
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value;
// Replace the first segment (the locale) with the new one
// e.g. /en/about -> /fr/about
const segments = pathname.split('/');
segments[1] = newLocale;
const newPath = segments.join('/');
router.push(newPath);
};
return (
<div className="fixed top-4 right-4 z-50">
<select
onChange={handleChange}
value={currentLocale}
className="p-2 border rounded bg-white shadow text-black"
>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
</div>
);
}
Step 6: The Main Page
Finally, update your app/[locale]/page.tsx to use the translations and include the switcher.
// app/[locale]/page.tsx
import {useTranslations} from 'next-intl';
import LanguageSwitcher from '../../components/LanguageSwitcher';
export default function Index() {
const t = useTranslations('Index');
return (
<div className="flex flex-col items-center justify-center min-h-screen py-2">
<LanguageSwitcher />
<main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
<h1 className="text-6xl font-bold">
{t('title')}
</h1>
<p className="mt-3 text-2xl">
{t('description')}
</p>
</main>
</div>
);
}
How to Run
- Save all files.
- Run
npm run dev.
- Go to
http://localhost:3000.
- It should automatically redirect to
http://localhost:3000/en.
- Use the dropdown in the top right to switch to French (
/fr) or Spanish (/es).
- The text updates immediately based on the selected JSON file.