Files
skills/docs/localization/i18n/i18n-detector/src/default-chain/default-chain.md
2026-05-29 08:20:56 +01:00

2.8 KiB

default-chain.ts — canonical detector-chain factory

(no submodules)

Purpose

defaultDetectorChain(options) builds the canonical 8-or-9 entry detector chain consumed by <TranslationProvider> and useLocaleDetection (and any other chain consumer that wants a sensible default without enumerating every detector). The factory returns a fresh LocaleDetector[] on every call so callers can mutate or filter the result without affecting subsequent invocations.

The order is deliberate: explicit user signals (querystring, backend preference, cookie, localStorage) come first, followed by shell-rendered hints (htmlLang), browser preferences (acceptLanguage, navigator), geolocation (cloudflareIpGeo), and finally the unconditional fallback.

Features

  • 8-entry chain when userPreferenceEndpoint is omitted; 9-entry chain when it is supplied. The user-preference detector slots in second so authenticated users' saved preferences beat every device-bound signal.
  • Fresh array per call — callers can .filter / .splice / .concat without affecting subsequent invocations.
  • Fallback always last; the factory wires fallbackDetector(options.fallback) as the terminal entry.
  • Every detector is constructed with default options — consumers that need custom names / paths / endpoints assemble their own chain.

Usage: Basic Example

import {
    createDetectorChain,
    defaultDetectorChain,
} from "@suaveplan/i18n-detector";

const chain = createDetectorChain(
    defaultDetectorChain({ fallback: "en-GB" })
);

Usage: Advanced Example

import {
    createDetectorChain,
    defaultDetectorChain,
} from "@suaveplan/i18n-detector";

const chain = createDetectorChain(
    defaultDetectorChain({
        fallback: "en-GB",
        userPreferenceEndpoint: "/api/me/locale",
    }),
    { throwOnExhausted: true }
);

// Or filter to remove a detector that does not fit the deployment.
const detectors = defaultDetectorChain({ fallback: "en-GB" }).filter(
    (d) => d.name !== "cloudflareIpGeo"
);

API Reference

  • defaultDetectorChain(options): LocaleDetector[] — fresh array per call.
  • DefaultDetectorChainOptions.fallback: string — required.
  • DefaultDetectorChainOptions.userPreferenceEndpoint?: string — enables the user-preference detector when set.

Implementation Notes

  • The fallback is constructed via fallbackDetector(...) which validates the locale at chain-build time, so a misconfigured fallback surfaces immediately rather than at the first request.
  • The factory makes no assumptions about cookie name, storage key, querystring param name, or geolocation header. Consumers that need custom configuration assemble their own chain by importing each detector directly.