I want to implement a dynamic language switch and SEO-friendly locale routes, so I'll choose App Router with next-intl, which integrates well with dynamic locale segments and middleware. For beginners, next-i18next or react-intl could also work, but recent documentation favors next-intl. I plan to provide examples using app/[locale]/layout.tsx, middleware.ts, and language switcher functions like usePathname and useRouter. The folder structure will include configurations in next.config.mjs and the new routing format in i18n.ts.Outlining localization setup
I need to recall the setup for localization using next-intl. For the App Router, I'd create a i18n.ts file that imports request configuration with locale messages from JSON files. My middleware.ts will define supported locales like English and German, setting up the middleware correctly.
Next, in app/[locale]/layout.tsx, I will utilize NextIntlClientProvider to provide locale-specific messages to my application. Additionally, in app/[locale]/page.tsx, I’ll use useTranslations for localized content on the homepage, noting that there are separate hooks for server and client components.Clarifying component setups
I've realized that while the page is a server component, useTranslations is a client hook that requires 'use client'. I might keep the page.tsx as a server component and use the getTranslations server function from next-intl. In v3, I can utilize both server and client exports appropriately.
For app/[locale]/page.tsx, I'll create an IndexPage function that fetches translations. Meanwhile, I'll implement a dynamic language switcher in a client component (LanguageSwitcher.tsx) using hooks like usePathname, useRouter, and useLocale from next-intl.Building locale paths
When the user selects a new locale (nextLocale), I need to update the path with pathname.replace(/locale‘,‘/{nextLocale}). However, I need to keep in mind that usePathname from 'next/navigation' returns paths with the leading locale, which means I might need to parse segments.
A simpler option could be using Link from next-intl/link, which manages locale automatically. Although it defaults to root paths, I can still use Link to correctly handle locale changes while preserving the existing path. To maintain the current path with variable segments, I can set href={pathname} accordingly.Implementing dynamic localization
To enable dynamic language switching, I'll use usePathname to get the current path. Using next-intl/link, I can create links that properly handle locale changes. For instance, I will set up a LanguageSwitcher component that offers options for English and German.
Also, I need to set up my localization middleware. The main steps involve creating i18n.ts for configuration and middleware.ts using createMiddleware. Additionally, I'll define translation messages in JSON files (like messages/en.json and messages/de.json) and implement required components to switch languages dynamically while storing user preferences.
I'm aiming to keep things concise but detailed enough to guide anyone through setting this up with Next.js.Setting up localization with Next.js
For generateStaticParams, I’ll create paths for each locale in app/[locale]/page.tsx, which uses getTranslations to retrieve the necessary translations.
I need to utilize unstable_setRequestLocale(locale) for accurate locale management in nested components. Also, the LanguageSwitcher will use useLocale to track the current locale.
In terms of structure, the translation messages will be organized in JSON files, and I must ensure the correct path for imports. The middleware configuration must also exclude specific Next.js assets to avoid interception.
I’ll keep this explanation straightforward and focused on the essential code. Below is a minimal, working setup for a Next.js (App Router) app with:
Localized routes (e.g. /en, /de)
JSON-based translations
A language switcher that changes the UI language without a full reload and keeps the current path
4. Add i18n middleware for locale detection & routing
Create middleware.ts in the root:
ts
// middleware.ts
import createMiddleware from 'next-intl/middleware';
import {locales, defaultLocale} from './i18n';
export default createMiddleware({
locales,
defaultLocale,
// Optional: enable auto-locale detection from Accept-Language
localeDetection: true
});
export const config = {
// Skip _next, assets, and API routes
matcher: ['/((?!api|_next|.*\\..*).*)']
};
This will:
Redirect / → /en (default) or detected locale
Keep locale in the URL (/en/..., /de/...)
5. Add translation messages
Create a messages folder at the project root:
bash
mkdir messages
messages/en.json:
json
{
"Index": {
"title": "Welcome",
"description": "This is the English version of the app."
},
"Nav": {
"home": "Home",
"about": "About",
"switchLanguage": "Sprache: Deutsch"
}
}
messages/de.json:
json
{
"Index": {
"title": "Willkommen",
"description": "Dies ist die deutsche Version der App."
},
"Nav": {
"home": "Startseite",
"about": "Über uns",
"switchLanguage": "Language: English"
}
}
You can structure these JSON files however you like; here we use simple namespaces (Index, Nav).
6. Set up the localized root layout
Create app/[locale]/layout.tsx (this will be your root layout):
tsx
// app/[locale]/layout.tsx
import {NextIntlClientProvider} from 'next-intl';
import {ReactNode} from 'react';
import {notFound} from 'next/navigation';
import {locales, type Locale} from '../../i18n';
import LanguageSwitcher from '../../components/LanguageSwitcher';
export function generateStaticParams() {
return locales.map((locale) => ({locale}));
}
export default async function LocaleLayout({
children,
params
}: {
children: ReactNode;
params: {locale: Locale};
}) {
const {locale} = params;
// Validate locale
if (!locales.includes(locale)) {
notFound();
}
let messages;
try {
messages = (await import(`../../messages/${locale}.json`)).default;
} catch (error) {
notFound();
}
return (
<html lang={locale}>
<body>
<NextIntlClientProvider locale={locale} messages={messages}>
{/* Put global UI here, e.g. nav */}
<header
style={{
padding: '1rem',
borderBottom: '1px solid #ddd',
display: 'flex',
justifyContent: 'space-between'
}}
>
<nav>
{/* You can add translated links here later */}
</nav>
<LanguageSwitcher />
</header>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
Notes:
NextIntlClientProvider makes translations and useLocale available in client components.
generateStaticParams prebuilds pages for each locale.
You do not need app/layout.tsx if [locale]/layout.tsx is at the top level; [locale] is your root segment.
7. Create a translated page
Create app/[locale]/page.tsx:
tsx
// app/[locale]/page.tsx
import {getTranslations} from 'next-intl/server';
import type {Locale} from '../../i18n';
export default async function HomePage({
params
}: {
params: {locale: Locale};
}) {
const t = await getTranslations({locale: params.locale, namespace: 'Index'});
return (
<main style={{padding: '2rem'}}>
<h1>{t('title')}</h1>
<p>{t('description')}</p>
</main>
);
}
This is a server component, using getTranslations from next-intl/server.
8. Add a dynamic language switcher
Create components/LanguageSwitcher.tsx:
tsx
// components/LanguageSwitcher.tsx
'use client';
import {useLocale} from 'next-intl';
import Link from 'next-intl/link';
import {usePathname} from 'next/navigation';
import {locales, type Locale} from '../i18n';
export default function LanguageSwitcher() {
const locale = useLocale() as Locale;
const pathname = usePathname();
// Example: two-locale toggle; for more locales use a select/dropdown
const otherLocales = locales.filter((l) => l !== locale);
return (
<div style={{display: 'flex', gap: '0.5rem', alignItems: 'center'}}>
<span style={{fontSize: '0.9rem'}}>Language:</span>
{otherLocales.map((l) => (
<Link
key={l}
href={pathname}
locale={l}
style={{textDecoration: 'underline', cursor: 'pointer'}}
>
{l.toUpperCase()}
</Link>
))}
</div>
);
}
What this does:
useLocale() gets the current locale from NextIntlClientProvider.
usePathname() gets the current path (/en, /en/about, etc.).
next-intl/link’s Link with locale={l} generates the same path in another locale:
e.g. from /en → /de
from /en/about → /de/about
This is your dynamic language switcher. It updates the URL and the UI language in a single navigation (no full reload).
9. Optional: a translated navigation bar
If you want navigation links to also be translated, create components/Nav.tsx:
tsx
// components/Nav.tsx
'use client';
import Link from 'next-intl/link';
import {useTranslations} from 'next-intl';
export default function Nav() {
const t = useTranslations('Nav');
return (
<nav style={{display: 'flex', gap: '1rem'}}>
<Link href="/">{t('home')}</Link>
<Link href="/about">{t('about')}</Link>
</nav>
);
}
Then import and use it in app/[locale]/layout.tsx header:
tsx
// ...
import Nav from '../../components/Nav';
// inside <header>:
<header /* ... */>
<Nav />
<LanguageSwitcher />
</header>
You’d also create app/[locale]/about/page.tsx and add Nav strings in messages/*.json.
10. Run the app
bash
npm run dev
Visit:
http://localhost:3000/ → auto-redirect to /en (or locale from browser)
Click the language switcher link → URL changes to /de and content switches to German.
If you tell me:
which locales you actually need, and
whether you want to store the language in cookies or user profile,
I can extend this with persistence, SEO meta tags per locale, and localized generateMetadata.