Replace the contents of the following files (delete any others in app/ except globals.css and favicon.ico if present). Then run npm run dev and visit http://localhost:3000.
middleware.ts (create in project root)
typescript
import { NextRequest, NextResponse } from 'next/server';
import type { NextUrl } from 'next/dist/server/web/next-url.js';
const locales = ['en', 'fr'] as const;
const defaultLocale = 'en';
function getLocale(request: NextRequest): string | null {
// 1. Cookie
let locale = request.cookies.get('NEXT_LOCALE')?.value;
// 2. Accept-Language header
if (!locale) {
const acceptLanguage = request.headers.get('accept-language');
if (acceptLanguage) {
const language = acceptLanguage.split(',')[0].split('-')[0].toLowerCase();
if (locales.includes(language as any)) {
locale = language;
}
}
}
return locale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Check if the pathname has a valid locale prefix
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (!pathnameHasLocale) {
// Redirect to include the locale
const locale = getLocale(request) ?? defaultLocale;
const newPath = `/${locale}${pathname === '/' ? '' : pathname}`;
return NextResponse.redirect(new URL(newPath, request.url));
}
// Extract and validate the locale from the pathname
const pathnameLocale = pathname.split('/')[1] as typeof locales[number] | undefined;
if (!pathnameLocale || !locales.includes(pathnameLocale)) {
// Invalid locale, redirect to default
const newPath = `/${defaultLocale}${pathname.slice(pathnameLocale!.length + 1)}`;
return NextResponse.redirect(new URL(newPath, request.url));
}
// Set the locale cookie for future requests
const response = NextResponse.next();
response.cookies.set('NEXT_LOCALE', pathnameLocale, {
path: '/',
maxAge: 60 * 60 * 24 * 30, // 30 days
});
return response;
}
export const config = {
// Matcher ignoring `/_path-to-next` and `/api/`, files matching `\.\w+$`
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)'],
};
app/layout.tsx
tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
app/[locale]/layout.tsx
tsx
import type { Metadata, PropsWithChildren } from 'next';
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string }>;
}): Promise<Metadata> {
const { locale } = await params;
return {
metadataBase: new URL('http://localhost:3000'), // Replace with your domain in production
alternates: {
canonical: `/${locale}`,
languages: {
'en-US': '/en',
'fr-FR': '/fr',
},
},
};
}
export default function LocaleLayout({
children,
params,
}: PropsWithChildren<{ params: { locale: string } }>) {
return (
<html lang={params.locale} suppressHydrationWarning>
<body>{children}</body>
</html>
);
}
app/[locale]/page.tsx
tsx
import Link from 'next/link';
const i18n = {
en: {
title: 'Welcome',
description: 'This is an internationalized Next.js app using middleware.',
switchTo: 'Switch to',
},
fr: {
title: 'Bienvenue',
description: "Ceci est une application Next.js internationalisée utilisant du middleware.",
switchTo: 'Passer à',
},
} as const;
export async function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'fr' }];
}
export default function Page({ params }: { params: { locale: string } }) {
const messages = i18n[params.locale as keyof typeof i18n];
return (
<main style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
<h1>{messages.title}</h1>
<p>{messages.description}</p>
<p>
<strong>Current locale:</strong> {params.locale.toUpperCase()}
</p>
<nav style={{ marginTop: '2rem' }}>
<Link
href="/en"
style={{ marginRight: '1rem', fontWeight: params.locale === 'en' ? 'bold' : 'normal' }}
>
🇺🇸 {messages.switchTo} English
</Link>
|
<Link
href="/fr"
style={{ marginLeft: '1rem', fontWeight: params.locale === 'fr' ? 'bold' : 'normal' }}
>
🇫🇷 {messages.switchTo} Français
</Link>
</nav>
<p style={{ marginTop: '2rem', fontSize: '0.875rem', color: '#666' }}>
💡 Test by changing your browser language to French, refreshing, or visiting <code>/</code>.
Middleware detects locale from cookie > Accept-Language > default (<code>en</code>).
</p>
</main>
);
}
How it works
Middleware: Runs on matching paths. Detects/redirects to locale prefix (/en, /fr). Prioritizes cookie → Accept-Language header → default (en). Sets cookie on valid requests.
Routing: All pages under app/[locale]/. Root / redirects to /en.
Static Generation: generateStaticParams pre-builds /en and /fr.
SEO: Dynamic alternates for canonical/hreflang.
Testing:
Visit / → redirects to /en.
Click "Français" → navigates to /fr, sets cookie.
Change browser lang to French (e.g., Chrome: Settings → Languages), hard refresh → /fr.
Invalid /de → redirects to /en.
/foo → redirects to /en/foo (404 if no page).
This is production-ready for basic i18n. Extend with next-intl for full i18n (translations, date formatting).