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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Content negotiation ranks the client's stated language preferences by quality before picking a match.
- 2Edge middleware can rewrite navigation by cloning the request URL and issuing a redirect.
- 3Persisting the chosen locale in a cookie skips renegotiation on every subsequent request.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/locale-routing-with-next-js-middleware-explained-javascript-8ddc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.