Focusing on User Needs
I've been drilling down on user requirements, specifically the need for dynamic language switching in a multi-language Next.js app. I'm focusing on simplicity and practicality, trying to figure out the best guide structure. I'm prioritizing clarity for new users, so that they can avoid common pitfalls. The goal is to make the guide very intuitive for users.
Evaluating Library Choices
I've zeroed in on next-intl as the best approach. It's the strongest choice for the App Router and provides type safety. react-i18next feels complex with Server Components, and next-i18n-router is too limited for my needs. The next step will be setting up a new Next.js project.
Structuring the Guide Content
I'm now outlining the steps in a logical sequence. Installation will come first, followed by configuration, which includes defining locales and setting up next.config.mjs. Then, the middleware setup and translation files. I'm prioritizing server components for initial content rendering, while a client-side language switcher will be offered as a bonus. Finally, I'll walk through a basic npx create-next-app project with the dependencies and file structure, demonstrating the overall implementation.
Mapping Out Code Samples
I'm deep into the code examples now. I'm focusing on the i18n.ts configuration to load the appropriate JSON files based on the locale. Also, next.config.mjs must be wrapped with withNextIntl. The middleware setup using createMiddleware is next on the list, defining locales and the default. I'm thinking about the layout now. For simplicity, I will stick with server components initially, but the NextIntlClientProvider is a must if they want client-side features, like language switching. The language switcher will utilize usePathname and useRouter from next.
Detailing Code Snippets
I'm now zeroing in on the finer points of the code, specifically the client-side language switcher component. I need a <select> element to let users pick their preferred language. The onChange event will update the URL path with the new locale. I'm clarifying how next-intl/client provides the necessary wrappers, and I'll emphasize that the component must be a "use client" component. I'm double-checking the example syntax for en.json and the page component, and clarifying the setup for the switcher, which uses usePathname and useRouter from next. I also intend to add explanations and contextualization for why we do each step, and emphasize the location of page.tsx.
Addressing [Locale] Folder
I'm now zeroing in on a crucial detail: the [locale] folder. If it's not present, nothing works, so this will be emphasized. The guide is almost done. I'll add a "How to run" section and a summary, finalizing the content.
This is a comprehensive guide to building a Next.js application (using the App Router) with internationalization (i18n) and a dynamic language switcher.
We will use next-intl. It is currently the most robust, type-safe, and standard library for handling i18n in the Next.js App Router.
Prerequisites
- Node.js installed (version 18+ recommended).
Step 1: Setup the Project
Create a new Next.js app using the App Router.
npx create-next-app@latest my-i18n-app
# Select Yes for TypeScript, ESLint, Tailwind, and App Router.
# Select No for 'src' directory (or adjust paths below if you say Yes).
Install the translation library:
cd my-i18n-app
npm install next-intl
Step 2: folder Structure
We need to reorganize the folder structure to support localized routing (e.g., /en/about, /fr/about).
- Create a
messages folder in the root directory.
- Your
app folder needs a dynamic segment [locale].
Your structure should look like this:
my-i18n-app/
├── messages/
│ ├── en.json
│ └── es.json
├── app/
│ └── [locale]/ <-- Move page.tsx and layout.tsx inside here
│ ├── layout.tsx
│ └── page.tsx
├── i18n.ts <-- Create this file in root
├── middleware.ts <-- Create this file in root
└── next.config.mjs
Step 3: Define Translations
Create your translation files in the messages folder.
messages/en.json
{
"HomePage": {
"title": "Hello World!",
"description": "Welcome to our multilingual app."
},
"Switcher": {
"label": "Choose Language"
}
}
messages/es.json
{
"HomePage": {
"title": "¡Hola Mundo!",
"description": "Bienvenido a nuestra aplicación multilingüe."
},
"Switcher": {
"label": "Elige el idioma"
}
}
Step 4: Configuration
1. Create i18n.ts
This file loads the translation file based on the user's locale request.
// i18n.ts
import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
// Can be imported from a shared config
const locales = ['en', 'es'];
export default getRequestConfig(async ({locale}) => {
// Validate that the incoming `locale` parameter is valid
if (!locales.includes(locale as any)) notFound();
return {
messages: (await import(`./messages/${locale}.json`)).default
};
});
2. Update next.config.mjs
Apply the plugin to the Next.js config.
// next.config.mjs
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNextIntl(nextConfig);
Step 5: Middleware
The middleware intercepts requests and appends the locale to the URL (e.g., redirecting / to /en).
Create middleware.ts in the root directory:
// middleware.ts
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
// A list of all locales that are supported
locales: ['en', 'es'],
// Used when no locale matches
defaultLocale: 'en'
});
export const config = {
// Match only internationalized pathnames
matcher: ['/', '/(es|en)/:path*']
};
Step 6: Configure the Layout
Move your layout.tsx and page.tsx inside app/[locale]/.
Update app/[locale]/layout.tsx to handle the dynamic language parameter and provide the translation context.
// 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};
}) {
// Providing all messages to the client
// side is the easiest way to get started
const messages = await getMessages();
return (
<html lang={locale}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
Step 7: Create the Dynamic Language Switcher
We need a client component to change the URL without a hard refresh.
Create app/components/LanguageSwitcher.tsx:
'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter, usePathname } from 'next/navigation';
import { ChangeEvent, useTransition } from 'react';
export default function LanguageSwitcher() {
const t = useTranslations('Switcher');
const locale = useLocale();
const router = useRouter();
const pathname = usePathname();
const [isPending, startTransition] = useTransition();
const onSelectChange = (e: ChangeEvent<HTMLSelectElement>) => {
const nextLocale = e.target.value;
startTransition(() => {
// Replace the locale in the pathname
// e.g., /en/about -> /es/about
// Note: If you use the `next-intl` navigation wrapper, this logic
// is slightly different, but this works for standard Next.js router.
// Remove the current locale from the path
const pathWithoutLocale = pathname.replace(`/${locale}`, '') || '/';
// Construct the new path
const newPath = `/${nextLocale}${pathWithoutLocale}`;
router.replace(newPath);
});
};
return (
<label className="border-2 rounded">
<p className="sr-only">{t('label')}</p>
<select
defaultValue={locale}
className="bg-transparent py-2 px-4 cursor-pointer"
onChange={onSelectChange}
disabled={isPending}
>
<option value="en">English</option>
<option value="es">Español</option>
</select>
</label>
);
}
Step 8: Build the Page
Now, let's update the main page app/[locale]/page.tsx to use translations and display the switcher.
import { useTranslations } from 'next-intl';
import LanguageSwitcher from '../../components/LanguageSwitcher'; // Adjust path
export default function HomePage() {
// Connect to the "HomePage" namespace defined in your JSON files
const t = useTranslations('HomePage');
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24">
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
<LanguageSwitcher />
</div>
<div className="mt-10 text-center">
<h1 className="text-4xl font-bold mb-4">{t('title')}</h1>
<p className="text-xl">{t('description')}</p>
</div>
</main>
);
}
Step 9: Run the App
npm run dev
- Visit
http://localhost:3000.
- You should be automatically redirected to
http://localhost:3000/en.
- You will see "Hello World".
- Use the dropdown to select "Español".
- The URL will change to
/es and the text will update to "¡Hola Mundo!" instantly without a full page reload.
Key Concepts Used
- Middleware: Handles the detection of the browser language and redirects URLs (e.g.,
/ -> /en).
- Dynamic Route
[locale]: Allows Next.js to treat the language prefix as a parameter easily accessible in server components and layouts.
useTranslations: The hook provided by next-intl to access your JSON keys.
- Server vs Client: We loaded messages on the server in the Layout, then passed them to the
NextIntlClientProvider. This allows both Server Components (like page.tsx) and Client Components (like LanguageSwitcher.tsx) to access translations efficiently.