Start
All articles
TechnicalPublished on · 3 min read

i18n in the Next.js App Router without a library: proxy, JSON, hreflang

How this site serves Portuguese, English and Spanish on Next.js 16 with JSON dictionaries, an Accept-Language proxy, generateStaticParams and hreflang.

BySenior Developer & Tech Lead

This article shows how to serve a site in Portuguese, English and Spanish on Next.js 16 without installing an i18n library. It is the same design I use on this portfolio: JSON dictionaries, a proxy that negotiates the language, and static routes per language. It is for developers, and for anyone who wants to understand what they are buying when someone says "the site needs to be multilingual".

When to skip the library (and when not to)

For a company site, a portfolio or a landing page, the requirements are small: a language prefix in the URL, translated text and the right tags for Google. That fits in three small files and adds no dependency to maintain.

A library starts paying off when the problem changes:

Need Without a library With a library
Fixed text in 2–5 languages Works well Unnecessary
Plurals and gender (ICU) You write it by hand Solved
Translated URLs (/sobre vs /about) Laborious Supported by some
Many translators and a review workflow JSON files get in the way Dedicated platforms

If your case sits in the first two rows, go ahead. The official Next.js internationalization guide describes the same foundation (dictionaries, proxy and a dynamic segment) and lists libraries for the other cases.

The foundation: a [locale] segment and the language list

Every route lives inside src/app/[locale]/. The single source for supported languages is a config file, which also negotiates the language from the Accept-Language header:

// src/i18n/config.ts
export const locales = ["pt", "en", "es"] as const;

export type Locale = (typeof locales)[number];

export const defaultLocale: Locale = "pt";

/** BCP-47 tag used in <html lang> and in alternates (hreflang). */
export const localeTags: Record<Locale, string> = {
  pt: "pt-BR",
  en: "en-US",
  es: "es-ES",
};

export function isLocale(value: string | undefined): value is Locale {
  return !!value && (locales as readonly string[]).includes(value);
}

/** "es-419,es;q=0.9,en;q=0.8" -> "es" */
export function resolveLocale(acceptLanguage: string | null): Locale {
  if (!acceptLanguage) return defaultLocale;

  const ranked = acceptLanguage
    .split(",")
    .map((part) => {
      const [tag, ...params] = part.trim().split(";");
      const q = params.find((p) => p.trim().startsWith("q="));
      return {
        tag: tag.trim().toLowerCase(),
        quality: q ? Number.parseFloat(q.split("=")[1]) || 0 : 1,
      };
    })
    .sort((a, b) => b.quality - a.quality);

  for (const { tag } of ranked) {
    const base = tag.split("-")[0];
    if (isLocale(base)) return base;
  }

  return defaultLocale;
}

isLocale is a type guard: after it, TypeScript knows the string is a Locale. That avoids as casts scattered around and acts as the barrier against URLs like /fr.

JSON dictionaries typed by the source language

Each language is a JSON file (pt.json, en.json, es.json) with the same structure. The dictionary type comes from the Portuguese file, so autocomplete and the compiler work with the real keys:

// src/i18n/dictionaries.ts
import en from "@/content/en.json";
import es from "@/content/es.json";
import pt from "@/content/pt.json";

import type { Locale } from "./config";

/** The pt-BR dictionary is the source of truth for typing. */
export type Dictionary = typeof pt;

const dictionaries = { pt, en, es } as unknown as Record<Locale, Dictionary>;

export function getDictionary(locale: Locale): Dictionary {
  return dictionaries[locale] ?? dictionaries.pt;
}

Because getDictionary runs in Server Components, the JSON does not ship whole to the browser. When you pass text to a Client Component, send only the slice it needs (dict.stack, not dict), because whatever becomes a prop is serialized and downloaded by the user.

The as unknown as has a cost: it silences TypeScript when en.json or es.json miss a key that exists in pt.json. The result is an undefined in production. Cover that with a test that compares the keys of the three files.

Negotiating the language in the proxy

At the root (/) and on any route without a prefix, the proxy redirects to the browser's preferred language. In Next.js 16 the old middleware was renamed to proxy, and it runs on the Node.js runtime by default:

// src/proxy.ts
import { NextResponse, type NextRequest } from "next/server";

import { locales, resolveLocale } from "@/i18n/config";

const PUBLIC_FILE = /\.(.*)$/;

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  if (
    pathname.startsWith("/_next") ||
    pathname.startsWith("/api") ||
    PUBLIC_FILE.test(pathname)
  ) {
    return NextResponse.next();
  }

  const hasLocale = locales.some(
    (locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`),
  );

  if (hasLocale) return NextResponse.next();

  const locale = resolveLocale(request.headers.get("accept-language"));
  const url = request.nextUrl.clone();
  url.pathname = `/${locale}${pathname === "/" ? "" : pathname}`;

  return NextResponse.redirect(url);
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};

The redirect keeps the path: /blog becomes /pt/blog (or /en/blog), so the visitor does not lose the page they wanted. The matcher excludes static files so the proxy does not run on every image.

Static routes, lang and hreflang

The layout in [locale] does three things: it generates one static page per language, validates the parameter, and tells Google about the equivalent versions of the page.

// src/app/[locale]/layout.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";

import { isLocale, locales, localeTags } from "@/i18n/config";
import { getDictionary } from "@/i18n/dictionaries";

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;
  if (!isLocale(locale)) return {};

  const dict = getDictionary(locale);

  return {
    title: dict.meta.title,
    description: dict.meta.description,
    alternates: {
      canonical: `/${locale}`,
      languages: Object.fromEntries(
        locales.map((code) => [localeTags[code], `/${code}`]),
      ),
    },
  };
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  if (!isLocale(locale)) notFound();

  return (
    <html lang={localeTags[locale]}>
      <body>{children}</body>
    </html>
  );
}

Three details that are often forgotten:

  • params is a Promise in the current App Router; without the await, you read the wrong object.
  • <html lang> must reflect the page language. Screen readers and automatic translators depend on it.
  • alternates.languages generates the hreflang tags. Each version must point to all the others, and the same goes for the sitemap, where each URL lists its equivalents.

What this approach does not do

Being direct about the limits of this solution:

  • q=0 is not honored. In resolveLocale, an en;q=0 ("not acceptable") is still a candidate, because the value falls to 0 and the tag stays in the list. For a content site the impact is small; if it matters to you, drop entries with quality === 0.
  • Region is discarded. pt-PT and pt-BR both become pt; es-419 becomes es.
  • No plurals, gender or ICU formatting. You handle dates and numbers with Intl, using the tag from localeTags.
  • URLs are not translated. The path changes only by prefix (/en/blog), not by word.
  • The redirect depends on a header. Test with curl -H "Accept-Language: es" -I http://localhost:3000/ to confirm the destination.

How to decide for your project

Use this skeleton if the site has few languages, mostly fixed text, and you want zero extra dependencies. Before publishing, check:

  1. All routes live inside [locale] and the proxy redirects anything without a prefix.
  2. generateStaticParams lists every language and isLocale blocks the rest with notFound().
  3. <html lang>, hreflang and the sitemap use the same tags.
  4. A test fails if a JSON file loses a key.

If the roadmap includes complex plurals, translated URLs or a translation team, adopt a library from the start: migrating later costs more than installing now.

Sources

Enjoyed the article? Share it

Get new articles by email

Practical guides and technical analysis, no spam. Unsubscribe anytime.

We only use your email to send the articles. You confirm the subscription by email and can unsubscribe at any time. Privacy Policy.

Keep reading