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
go
package middleware import ( "crypto/sha256"
Deduplicating concurrent requests in Gin
singleflight
request-coalescing
middleware
Advanced
8 steps
java
@Configuration @EnableRedisHttpSession(namespace = "myapp:sessions", maxInactiveIntervalInSeconds = 1800, flushMode = FlushMode.IMMEDIATE) public class SessionConfig {
Backing HTTP sessions with Redis in Spring
session-management
redis
distributed-state
Intermediate
7 steps
javascript
const express = require('express'); const cookieParser = require('cookie-parser'); const router = express.Router();
Remember-me login with signed cookies in Express
authentication
signed-cookies
sessions
Intermediate
9 steps
javascript
const TOKEN_SPECS = [ ["comment", /^\/\/[^\n]*|^\/\*[\s\S]*?\*\//], ["string", /^"(?:\\.|[^"\\])*"|^'(?:\\.|[^'\\])*'|^`(?:\\.|[^`\\])*`/], ["number", /^0[xX][\da-fA-F]+|^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/],
Building a syntax highlighter tokenizer
tokenizer
regular-expressions
lexing
Intermediate
8 steps
javascript
export async function compressImage(file, { maxWidth = 1600, maxHeight = 1600, quality = 0.8, mimeType = 'image/jpeg' } = {}) { const bitmap = await createImageBitmap(file); let { width, height } = bitmap;
Compressing images in the browser with canvas
canvas
image-processing
promises
Intermediate
7 steps
rust
use std::time::Duration; use axum::{ http::{header, HeaderValue, Request},
Serving fingerprinted assets in Axum
static-assets
http-caching
middleware
Intermediate
7 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.