Locale URL policy
Define locale prefixes, negotiate language preferences, and produce redirect and alternate-path decisions without coupling them to a framework.
A localized URL needs a consistent policy: which languages exist, how they appear in paths, and where a bare path should send the reader. @lingo.dev/locale-router makes those decisions with native Intl. Your server sends the redirect, and your application loads the chosen catalog.
Define supported locales and slugs #
npm install @lingo.dev/locale-router@0.2.1import { createLocaleRouter } from "@lingo.dev/locale-router";
const locales = createLocaleRouter(["en", "de", "pt-BR"] as const, {
defaultLocale: "en",
exclude: ["api", "assets"],
slugs: { "pt-BR": "br" },
});The locale pt-BR identifies Brazilian Portuguese; br is only its URL slug. Without an override, slugs are lowercase locale tags. Use valid tags, a default from the supported set, and distinct lowercase slugs. The constructor does not validate every conflicting configuration.
createLocaleRouter<L extends string>(locales, options) accepts a readonly locale array and returns LocaleRouter<L>. defaultLocale is required; exclude and slugs are optional. Exclusions match the first pathname segment. A first segment beginning with _ or containing . is also excluded, keeping internal and file paths outside localization.
Turn a bare URL into a redirect decision #
const target = locales.redirect(
new URL("https://example.com/account?tab=billing#details"),
"de-CH,de;q=0.8,en;q=0.5",
);
if (target) {
console.log(target.href);
}This produces https://example.com/de/account?tab=billing#details. The preference for Swiss German matches the supported German language. The helper returns a new URL; it does not send an HTTP response or set a cookie. Your server chooses the status and sends its location. A real HTTP request does not include the browser's fragment, even though the URL helper preserves one supplied to it.
If a saved preference should take priority, validate its locale tag through toLocale and pass the result as redirect's optional third argument. Do not pass an arbitrary string as a supported locale.
Inspect and build paths #
| Call with the policy above | Result |
|---|---|
locales.toLocale("pt_BR") | "pt-BR". Underscores normalize before exact locale matching. |
locales.toLocale("br") | undefined. A URL slug is not the locale tag. |
locales.split("/br/account") | { locale: "pt-BR", rest: "/account" }. |
locales.isLocalized("/account") | true. This means eligible for localization, not already prefixed. |
locales.prefix("/account", "de") | "/de/account". |
locales.prefix("/", "de") | "/de". |
locales.prefix("/api/status", "de") | "/api/status", unchanged. |
locales.canonical("/DE/account") | "/de/account". |
split returns undefined for an unrecognized first-segment slug. Give path methods a pathname, not a string containing query parameters or a hash.
prefix and alternates expect an unprefixed path. To change /br/account to German, split it and pass rest:
const current = locales.split("/br/account");
const germanPath = current ? locales.prefix(current.rest, "de") : undefined;The result is /de/account. Prefixing the original path directly can add a second locale segment.
Negotiate language preferences #
negotiate(acceptLanguage: string | null): L sorts positive preferences by quality and tries each in order. For each preference it checks an exact locale match, then a supported language match. If several supported regional locales share a language, their configured order can determine the language fallback.
Invalid quality values and zero-quality preferences are discarded. Invalid tags do not match, and a wildcard does not replace the default policy. If no preference matches, the method returns defaultLocale. This selects a language from stated preferences, not from geolocation.
Keep canonicalization separate from bare-path redirects #
canonical(pathname): string | undefined suggests a normalized slug for a recognized locale-like first segment. It is not a general canonical URL generator. redirect returns undefined for already prefixed paths, exclusions, and paths for which canonical can suggest a correction.
Handle /DE/account normalization separately if your application requires it. A server can replace the pathname on a copy of the request URL, preserving search, before sending its chosen redirect. TanStack's middleware handles bare-path negotiation but does not add this separate normalization step.
Generate alternate-language URLs #
const links = locales.alternates("/account").map(({ locale, pathname }) => ({
hrefLang: locale,
href: new URL(pathname, "https://example.com").href,
}));Use the site's trusted origin instead of the illustration. alternates returns one { locale, pathname } per supported locale plus x-default pointing to the default locale's path. The pt-BR language entry uses /br/account; the default English entry uses /en/account under this policy.
The caller renders these as metadata. TanStack head metadata adds canonical and Open Graph fields around this policy. The Next Pages adapter follows Next's different default-locale URL policy, so do not interchange their outputs.