javascript 49 lines · 10 steps

Locale routing with Next.js middleware

A Next.js middleware that redirects visitors to a locale-prefixed path based on cookie or Accept-Language.

Explained by highlit
1import { NextResponse } from 'next/server';
2 
3const locales = ['en', 'fr', 'de', 'es'];
4const defaultLocale = 'en';
5 
6function parseAcceptLanguage(header) {
7 if (!header) return [];
8 return header
9 .split(',')
10 .map((part) => {
11 const [tag, q = 'q=1'] = part.trim().split(';');
12 const quality = parseFloat(q.replace('q=', '')) || 0;
13 return { locale: tag.split('-')[0].toLowerCase(), quality };
14 })
15 .sort((a, b) => b.quality - a.quality);
16}
17 
18function negotiateLocale(header) {
19 for (const { locale } of parseAcceptLanguage(header)) {
20 if (locales.includes(locale)) return locale;
21 }
22 return defaultLocale;
23}
24 
25export function middleware(request) {
26 const { pathname } = request.nextUrl;
27 
28 const hasLocale = locales.some(
29 (locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`),
30 );
31 if (hasLocale) return NextResponse.next();
32 
33 const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
34 const locale =
35 cookieLocale && locales.includes(cookieLocale)
36 ? cookieLocale
37 : negotiateLocale(request.headers.get('accept-language'));
38 
39 const url = request.nextUrl.clone();
40 url.pathname = `/${locale}${pathname === '/' ? '' : pathname}`;
41 
42 const response = NextResponse.redirect(url);
43 response.cookies.set('NEXT_LOCALE', locale, { maxAge: 60 * 60 * 24 * 365 });
44 return response;
45}
46 
47export const config = {
48 matcher: ['/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)'],
49};
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Content negotiation ranks the client's stated language preferences by quality before picking a match.
  2. 2Edge middleware can rewrite navigation by cloning the request URL and issuing a redirect.
  3. 3Persisting the chosen locale in a cookie skips renegotiation on every subsequent request.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Locale routing with Next.js middleware — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code