Skip to the code

Send each visitor to their language

Mediumproxy.ts

Leaf and Kettle is now in English and French. Every page lives under app/[lang], so /en/teas and /fr/teas are the tea list in each language, and @/lib/i18n has the locales, ["en", "fr"], and the defaultLocale, "en". People still follow old links and type addresses without a language, like /teas/mint. Write proxy.ts to send them to theirs.

A path that already starts with a language, /en or /fr on its own or followed by /, goes on to its page: return NextResponse.next(). Pages like /fresh-picks and /english-breakfast only start with the same letters, so they have no language yet.

Any other path gets a 307 redirect to the same path and query with the language in front: /teas/mint?ref=mail goes to /fr/teas/mint?ref=mail, and / goes to /fr.

To pick the language, a NEXT_LOCALE cookie of en or fr comes first: the language picker sets it. Otherwise read the Accept-Language header, a comma-separated list of language tags like fr-CA,fr;q=0.9,en;q=0.8, each with an optional weight q from 0 to 1 (1 when it's missing). Go through the tags from the highest weight down, and in the listed order for equal weights; the first whose language, the part before any - in any case, is en or fr wins. A weight of 0 means not this one. When nothing matches, use en.

config.matcher keeps the proxy away from the API (/api/...), from Next.js's own files (/_next/...), and from any path with a dot in it, like /favicon.ico and /images/leaf.png.

GET /teas/mint?ref=mail   Accept-Language: de-DE,fr;q=0.8,en;q=0.5
→ 307  Location: http://localhost:3000/fr/teas/mint?ref=mail
 
GET /teas/mint   Cookie: NEXT_LOCALE=en   Accept-Language: fr
→ 307  Location: http://localhost:3000/en/teas/mint
 
GET /fr/teas/mint
→ goes on to app/[lang]/teas/[slug]/page.tsx

The app's other files

lib/i18n.ts, read-only. Import it as @/lib/i18n.

/** The languages the shop is written in. Every page lives under app/[lang], like app/[lang]/teas/page.tsx. */
export const locales = ["en", "fr"];
 
/** The language for visitors who ask for none of them. */
export const defaultLocale = "en";

What the tests check

  1. runs for pages, not the API, Next.js's files, or paths with a dot
    for (const path of ["/", "/teas", "/teas/mint", "/fr/teas", "/fresh-picks"]) expect(proxyRuns(path)).toBe(true);
    for (const path of ["/api/teas", "/_next/static/chunks/main.js", "/_next/image", "/favicon.ico", "/images/leaf.png", "/robots.txt"]) expect(proxyRuns(path)).toBe(false);
    
  2. puts the visitor's language in front, keeping the path and query
    const mint = await proxy(request("/teas/mint?ref=mail", { headers: { "accept-language": "fr-CA,fr;q=0.9,en;q=0.8" } }));
    expect(mint.status).toBe(307);
    expect(mint.headers.get("location")).toBe("http://localhost:3000/fr/teas/mint?ref=mail");
    const home = await proxy(request("/", { headers: { "accept-language": "en-GB,en;q=0.9" } }));
    expect(home.status).toBe(307);
    expect(home.headers.get("location")).toBe("http://localhost:3000/en");
    
  3. picks the shop language the visitor weighs highest
    const cases = [
      ["de-DE,fr;q=0.8,en;q=0.5", "fr"],
      ["en;q=0.3, FR-be;q=0.7", "fr"],
      ["ja, en-US;q=0.6, fr;q=0.6", "en"],
      ["fr;q=0, en;q=0.1", "en"],
      ["fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5", "fr"],
    ];
    for (const [header, locale] of cases) {
      const response = await proxy(request("/teas", { headers: { "accept-language": header } }));
      expect(response.headers.get("location")).toBe("http://localhost:3000/" + locale + "/teas");
    }
    
  4. falls back to English
    for (const headers of [{}, { "accept-language": "de-DE,ja;q=0.5" }, { "accept-language": "*" }, { "accept-language": "fr;q=0" }]) {
      const response = await proxy(request("/teas", { headers }));
      expect(response.headers.get("location")).toBe("http://localhost:3000/en/teas");
    }
    
  5. a NEXT_LOCALE cookie with a shop language wins over the header
    const french = await proxy(request("/teas", { headers: { cookie: "NEXT_LOCALE=fr", "accept-language": "en-US" } }));
    expect(french.headers.get("location")).toBe("http://localhost:3000/fr/teas");
    const english = await proxy(request("/teas", { headers: { cookie: "NEXT_LOCALE=en", "accept-language": "fr" } }));
    expect(english.headers.get("location")).toBe("http://localhost:3000/en/teas");
    const german = await proxy(request("/teas", { headers: { cookie: "NEXT_LOCALE=de", "accept-language": "fr" } }));
    expect(german.headers.get("location")).toBe("http://localhost:3000/fr/teas");
    
  6. paths with a language go on, paths that only share its letters don't
    for (const path of ["/en", "/fr", "/fr/teas/mint", "/en/account/orders?page=2"]) {
      const response = await proxy(request(path, { headers: { "accept-language": "fr" } }));
      // NextResponse.next() marks its answer with x-middleware-next: 1; returning nothing does the same.
      expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
    }
    const fresh = await proxy(request("/fresh-picks", { headers: { "accept-language": "fr" } }));
    expect(fresh.headers.get("location")).toBe("http://localhost:3000/fr/fresh-picks");
    const breakfast = await proxy(request("/english-breakfast", { headers: { "accept-language": "fr" } }));
    expect(breakfast.headers.get("location")).toBe("http://localhost:3000/fr/english-breakfast");
    

Learn more

proxy.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).