Skip to content
项目

关于

Zero-dependency i18n for Next.js App Router (Next.js 15/16, React 19). 27x-39x faster than next-intl, 82% smaller client JS, 99% smaller RSC payload.

网站与应用开发

这些数字如何统计

实测星标增长

24小时
0
7天
正在收集历史
15天
正在收集历史
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

next-fast-i18n

CI npm version license zero dependencies

Zero-dependency i18n for Next.js 15/16 App Router (React 19, TypeScript 7). A smaller, faster alternative to next-intl with full ICU parity across all locales, scoped RSC payloads, clean 308 routing, and deterministic CLDR formatting.

next-fast-i18n install command and benchmark results against next-intl

  • 17.5x to 27.6x faster rendering than next-intl even with AOT precompilation (29x to 37x faster vs next-intl defaults; 17.5x faster in end-to-end React 19 renderToString SSR across 10 languages)
  • Full ICU MessageFormat parity by default across all locales ({var}, 6-form CLDR plurals via native Intl.PluralRules + =N + offset:N, select, selectordinal, inline number/date/time + skeletons, ICU apostrophe escaping, nested t.rich() / t.markup(), t.raw(), and createFormatter with relativeTime/list/dateTimeRange)
  • Opt-in /lite subpath (next-fast-i18n/lite) for ultra-small bundles (2.66 KB gz provider + hooks, 4.05 KB gz full app with nav + deterministic CLDR formatter: 2x smaller than precompiled next-intl)
  • Smaller client JS even with full ICU vs precompiled next-intl, with zero next.config plugin (5.16 KB vs 5.23 KB gz for provider + hooks; 7.10 KB vs 7.92 KB gz with useFormatter + navigation; -58% to -84% vs next-intl defaults)
  • 99% smaller RSC payload vs passing full dictionaries (0.55 KB vs 67.2 KB) via built-in pickMessages() and <I18nMessages> deep-merging (both libraries support manual slicing; next-fast-i18n includes deep-merge islands out of the box)
  • Zero Alpine Docker #418 hydration drift with deterministic CLDR UTC date and integer formatters for en/de/fr/it and cached Intl fallback for all other locales
  • Plain 308 URL-only routing in Next.js 16 proxy.ts (middleware.ts) with no next.config plugin, no 307 cookie redirects, unconditional x-locale anti-spoofing, and open-redirect guards
  • 0 runtime dependencies (next and react are optional peer dependencies)

Built for AgenturScout at Magicspace.


Why we built next-fast-i18n

Running AgenturScout (a multilingual Next.js 16 directory in German, English, and French) surfaced four problems we kept hitting across Next.js i18n setups:

  1. RSC payload bloat: Passing a full locale dictionary into <NextIntlClientProvider> serialized 67 to 73 KB of JSON into every HTML response when client components only read 5 to 15 keys.
  2. Per-request SSR overhead: Re-parsing ICU syntax or re-creating per-render Intl memoizers on every SSR request added CPU time on pages with hundreds of translation calls.
  3. Alpine Linux vs browser React #418 errors: Minimal Docker images ship different ICU data than Chrome and Safari (such as narrow no-break spaces \u202f in French numbers or abbreviated month periods in German and French), causing hydration mismatches on dates and grouped numbers.
  4. Unexpected redirects and config plugins: Accept-Language and NEXT_LOCALE cookie 307 redirects, Link header bloat, and next-intl/plugin wrappers complicated SEO canonicals and Docker standalone builds.

next-fast-i18n solves all four with zero runtime dependencies and no next.config.ts plugin.


Benchmarks vs next-intl (default & AOT precompiled)

Before timing, every run verifies 4,212 exact parity checks across 10 languages (en, de, fr, it, es, pl, ru, ar, ja, zh) against both [email protected] defaults and [email protected] with ahead-of-time precompilation (icu-minify + use-intl/format-message/format-only), plus 48 CLDR dates, 10-locale React 19 renderToString HTML equality, and React 19 t.rich() rendering with zero key warnings. Timings are the median of 7 interleaved 3-way trials.

Note: next-intl maintainer Jan Amann also opened amannn/next-intl#2553 to optimize hot-path plain strings and argument caching after seeing these benchmarks; once released, next-intl plain-string timings will improve (~2.5x faster than 4.16.2).

Translation latency benchmark: next-fast-i18n vs next-intl default and precompiled

Client JS bundle and RSC payload benchmark: next-fast-i18n vs next-intl

Translation & SSR latency (median of 7 interleaved trials)

Measured on Bun 1.4.5 (arm64, macOS) against [email protected] (both default and precompile via use-intl/format-message/format-only + icu-minify).

Workload next-intl (default) next-intl (precompile) next-fast-i18n Speedup vs default Speedup vs precompile
W1 Full Page Warm (663 calls/loc) 217.04 us 171.86 us 7.49 us 29.0x 22.9x
W2 Cold Translator / Warm Dict 285.23 us 211.03 us 7.63 us 37.4x 27.6x
W3 Full Page True Cold (fresh JSON.parse) 280.75 us 202.08 us 37.57 us 7.5x 5.4x
W4 Sparse 5-Key Component (True Cold) 24.49 us 16.04 us 1.23 us 19.9x 13.0x
W5 Dynamic Plurals + Rich (Warm, 13 calls) 31.80 us 12.78 us 1.00 us 31.8x 12.8x
W6 Dynamic Plurals + Rich (True Cold, 13 calls) 148.14 us 104.76 us 5.86 us 25.3x 17.9x
W7 Full ICU Parity 10 Locales (ar/pl/ru/ja/zh/..., Warm) 44.65 us 13.02 us 2.88 us 15.5x 4.5x
W8 Full ICU Parity 10 Locales (True Cold) 257.19 us 189.51 us 9.31 us 27.6x 20.4x
W9 React 19 renderToString SSR Page (10 Locales) 203.47 us 166.22 us 9.52 us 21.4x 17.5x

Cross-checked on Node v24.22.2 (V8): 11.4x faster on plain full-page lookups and 20.3x faster on warm Full ICU (plural + select + selectordinal + currency + date + nested rich).

Apples-to-apples client JS bundle & RSC payload

Built with Bun.build --minify (react, react-dom, next externalized). Both gzip and brotli are reported.

Measurement Minified / Raw Gzip Brotli Delta vs next-intl default (gz)
next-intl default (Provider + hooks + useFormatter + nav) 53.00 KB 16.90 KB 14.84 KB baseline
next-intl precompile (Provider + hooks + useFormatter + nav) 20.46 KB 7.92 KB 7.03 KB -53.2%
next-fast-i18n/client (full ICU + I18nMessages + useFormatter + nav) 18.22 KB 7.10 KB 6.41 KB -58.0% (-10.4% vs precompile)
next-fast-i18n/lite/client (lite + I18nMessages + useFormatter + nav) 9.91 KB 4.05 KB 3.67 KB -76.1% (-48.9% vs precompile)
next-intl precompile (Provider + useTranslations + useLocale) 13.43 KB 5.23 KB 4.63 KB -69.1%
next-fast-i18n/client (full ICU, I18nProvider + useTranslations + useLocale) 12.93 KB 5.16 KB 4.65 KB -69.5% (-1.3% vs precompile)
next-fast-i18n/lite/client (lite, I18nProvider + useTranslations + useLocale) 6.02 KB 2.66 KB 2.42 KB -84.2% (-49.1% vs precompile)
RSC messages prop: full dictionary (en, raw JSON) 67.23 KB 5.82 KB 2.87 KB baseline
RSC messages prop: full dictionary (en, icu-minify precompiled) 67.45 KB 5.86 KB 2.84 KB +0.3% raw
RSC messages prop: scoped interactive island (pickMessages) 0.55 KB 0.34 KB 0.27 KB -99.2% raw
RSC messages prop: scoped public shell (pickMessages) 0.69 KB 0.28 KB 0.21 KB -99.0% raw

Note on RSC payloads: next-intl also supports manual message slicing via its Option 3 docs. The 67 KB vs 0.55 KB delta compares passing a full dictionary (the common default) vs scoped slices. next-fast-i18n includes pickMessages() and <I18nMessages> out of the box to deep-merge per-route islands into the root provider without re-sending shell keys.

Reproduce these numbers and regenerate the SVG charts locally:

bun run build
bun run bench

How it works

  • Adaptive WeakMap slot cache (FLATTEN_MISS_THRESHOLD = 12): Small client components that read 3 to 5 keys do direct dot-path lookups without paying to flatten the whole JSON dictionary. Once a dictionary hits 12 misses (like a full Server Component page), it flattens once into a Map for O(1) lookups.
  • Process-wide LocaleCache + SIMD scanning: Plain strings return straight from the map with zero parsing. Dynamic strings use indexOf("{") fast paths, compile once into compact tagged descriptors, and share lazily created native Intl.PluralRules / Intl.NumberFormat / Intl.DateTimeFormat instances across SSR requests (avoiding per-render cache churn and JSON.stringify memoization keys).
  • Prototype-safe resolution and merging: resolvePath, pickMessages, mergeMessages, and ICU select cases check Object.hasOwn / Object.create(null) and ignore __proto__, constructor, and prototype.
  • Depth-bounded TypeScript 7 (tsgo) types: MessageKey<T> and NamespaceKey<T> cap recursion at depth 6 (NextDepth = [1, 2, 3, 4, 5, never]) so large JSON dictionaries get autocomplete without hitting TS2589.

Trade-offs vs next-intl

Capability next-fast-i18n (default) next-fast-i18n/lite next-intl (precompile)
Runtime dependencies 0 0 use-intl, icu-minify
Client bundle (Provider + hooks + useFormatter + nav) 7.10 KB gz (6.41 br) 4.05 KB gz (3.67 br) 7.92 KB gz (7.03 br)
Client bundle (Provider + useTranslations + useLocale) 5.16 KB gz (4.65 br) 2.66 KB gz (2.42 br) 5.23 KB gz (4.63 br)
Next.js config plugin required No No Yes (experimental.messages.precompile)
t.raw() supported Yes Yes No
Scoped client message merging Built-in (pickMessages + <I18nMessages>) Built-in Manual slicing
Deterministic Alpine-safe CLDR dates/ints Built-in (en/de/fr/it) + Intl fallback Built-in + Intl fallback Relies on host Intl ICU
Full ICU (all-locale 6-form plurals, offset, select, selectordinal, number/date/time, skeletons, nested rich) Yes Subset ({var}, Western plural, flat rich) Yes (drops plural offset)
useFormatter (dateTime, dateTimeRange, number, relativeTime, list) Yes dateTime + number Yes
Per-locale translated pathnames (/about vs /ueber-uns) & useNow() Manual / app-level Manual / app-level Built-in

Use next-fast-i18n (default) for full ICU parity across all locales with zero dependencies, no next.config plugin, faster SSR (17.5x faster React 19 renderToString), and smaller client bundles than precompiled next-intl.

Use next-fast-i18n/lite (1-line import swap to next-fast-i18n/lite/client and next-fast-i18n/lite/server) when your app only needs {var}, Western plural, flat t.rich(), and deterministic dates/numbers and wants half the bundle size (2.66 KB gz provider + hooks, 4.05 KB gz full app).

Stick with next-intl if you need built-in per-locale translated URL slugs (/about vs /ueber-uns), useNow() live ticking relative-time hooks, or useExtracted PO/Crowdin extraction workflows.


Install

bun add next-fast-i18n
# or
npm install next-fast-i18n

No next.config.ts plugin needed.


Package entrypoints

Entrypoint Purpose
next-fast-i18n Core adaptive translator (createTranslator), pickMessages, mergeMessages, hasLocale, resolvePath, formatMessage, formatRichMessage, deterministic CLDR formatters (formatDateMedium, formatDateLong, formatInteger), routing helpers (localizeHref, stripLocalePrefix), and strict depth-bounded TypeScript 7 types (MessageKey<T>, NamespaceKey<T>, MessageAt<T, P>).
next-fast-i18n/server Server Component factory (createServerI18n), getTranslations / getT, getLocale, setRequestLocale, getClientMessages, getFormatter, and React 19 keyRichElement auto-keying.
next-fast-i18n/client "use client" context and hooks: <I18nProvider>, <I18nMessages>, useTranslations, createTypedTranslations, useLocale, useFormatter, createNavigation, Link, useRouter, usePathname.
next-fast-i18n/proxy Next.js 16 proxy.ts (middleware.ts) locale router (createLocaleProxy) with 308 default-locale stripping, req.nextUrl.clone() standalone rewrites, unconditional x-locale header overwrite, and open-redirect guards.
next-fast-i18n/lite Ultra-lightweight core ({var}, Western plural, flat t.rich(), pickMessages, deterministic CLDR dates/ints) for sites that do not need full ICU (2.66 KB gz client provider + hooks, 4.05 KB gz with nav + formatter).
next-fast-i18n/lite/server Server Component factory (createServerI18n, getTranslations / getT, getLocale, getClientMessages, getFormatter) backed by the lite engine.
next-fast-i18n/lite/client "use client" hooks and navigation backed by the lite engine (shares <I18nProvider> context with next-fast-i18n/client).

Quickstart (Next.js 16 App Router)

1. Define your locales and server i18n helper

// lib/config.ts
import type enMessages from "../messages/en.json";

export const LOCALES = ["en", "de", "fr"] as const;
export type Locale = (typeof LOCALES)[number];
export const DEFAULT_LOCALE: Locale = "en";
export const TRAILING_SLASH = false;

export type Messages = typeof enMessages;
// lib/i18n.ts
import { createServerI18n } from "next-fast-i18n/server";
import { DEFAULT_LOCALE, LOCALES, type Messages } from "./config";

export const {
  getClientMessages,
  getFormatter,
  getLocale,
  getMessages,
  getT,
  getTranslations,
  normalizeLocale,
  setRequestLocale,
} = createServerI18n<Messages, typeof LOCALES>({
  defaultLocale: DEFAULT_LOCALE,
  locales: LOCALES,
  loadMessages: locale => import(`../messages/${locale}.json`),
});

2. Wire proxy.ts (or middleware.ts)

// proxy.ts
import { createLocaleProxy } from "next-fast-i18n/proxy";
import { DEFAULT_LOCALE, LOCALES, TRAILING_SLASH } from "./lib/config";

export const config = {
  matcher: [
    "/((?!api|_next|_vercel|.*\\.(?:png|jpe?g|gif|webp|avif|svg|ico|woff2?|css|js|map|txt|xml)$).*)",
  ],
};

export default createLocaleProxy({
  defaultLocale: DEFAULT_LOCALE,
  locales: LOCALES,
  trailingSlash: TRAILING_SLASH,
});

Need custom auth, bot-gate, or redirect logic before locale routing? Call localeProxy.resolve(pathname, search) directly:

const localeProxy = createLocaleProxy({
  defaultLocale: DEFAULT_LOCALE,
  locales: LOCALES,
  trailingSlash: false,
});

const action = localeProxy.resolve(req.nextUrl.pathname, req.nextUrl.search);
// action is { type: "redirect", location, pathname, status: 308 }
//         | { type: "rewrite", pathname, locale }
//         | { type: "next", locale }

What createLocaleProxy handles:

  • Default-locale URLs (/en, /en/pricing?tier=pro) issue a single 308 redirect to / or /pricing?tier=pro.
  • Unprefixed URLs (/pricing) clone req.nextUrl (req.nextUrl.clone()) for internal rewrites so Next.js standalone in Docker avoids redirect loops.
  • x-locale is unconditionally overwritten on every forwarded request to block spoofed client headers.
  • Path boundaries are checked strictly so /english and /deutsch are never stripped as /en or /de.
  • Protocol-relative paths (/en//evil.com or //evil.com) are collapsed before redirecting so they cannot escape your origin.

3. Root locale layout with minimal shell payload

// app/[locale]/layout.tsx
import { hasLocale } from "next-fast-i18n";
import { I18nProvider } from "next-fast-i18n/client";
import { notFound } from "next/navigation";
import { DEFAULT_LOCALE, LOCALES, TRAILING_SLASH } from "@/lib/config";
import { getClientMessages, setRequestLocale } from "@/lib/i18n";

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

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

  setRequestLocale(locale);

  // Only serialize tiny shell namespaces to the browser (~0.3 KB).
  const shellMessages = await getClientMessages(locale, ["nav", "locale"]);

  return (
    <html lang={locale} translate="no">
      <body>
        <I18nProvider
          defaultLocale={DEFAULT_LOCALE}
          locale={locale}
          locales={LOCALES}
          messages={shellMessages}
          trailingSlash={TRAILING_SLASH}
        >
          {children}
        </I18nProvider>
      </body>
    </html>
  );
}

4. Server Components + scoped client islands (pickMessages & <I18nMessages>)

Keep static content on the server (0 KB client JS) and pass only route-specific namespaces to interactive client islands via <I18nMessages>:

// app/[locale]/page.tsx
import { I18nMessages } from "next-fast-i18n/client";
import { getClientMessages, getFormatter, getT, setRequestLocale } from "@/lib/i18n";
import { CostCalculator } from "./_components/cost-calculator";

export default async function Page({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);

  const [tHero, fmt, calcMessages] = await Promise.all([
    getT({ locale, namespace: "hero" }),
    getFormatter({ locale }),
    getClientMessages(locale, ["calculator"]),
  ]);

  return (
    <main>
      <h1>{tHero("title")}</h1>
      <p>
        {tHero.rich("richNote", {
          docs: chunks => <a href="#docs">{chunks}</a>,
        })}
      </p>
      <p>{fmt.dateTime(new Date("2026-11-29T12:00:00Z"), { dateStyle: "long" })}</p>

      {/* Deep-merges "calculator" into <I18nProvider> without duplicating root messages */}
      <I18nMessages messages={calcMessages}>
        <CostCalculator />
      </I18nMessages>
    </main>
  );
}

5. Pre-typed client hooks & navigation

// lib/navigation.ts
"use client";

import { createNavigation, createTypedTranslations } from "next-fast-i18n/client";
import { DEFAULT_LOCALE, LOCALES, type Messages, TRAILING_SLASH } from "./config";

export const useTranslations = createTypedTranslations<Messages>();

export const { getPathname, Link, localizeHref, stripLocalePrefix, usePathname, useRouter } =
  createNavigation({
    defaultLocale: DEFAULT_LOCALE,
    locales: LOCALES,
    trailingSlash: TRAILING_SLASH,
  });

TypeScript 7 key & namespace autocomplete

MessageKey<T>, NamespaceKey<T>, and MessageAt<T, P> cap recursion depth (NextDepth = [1, 2, 3, 4, 5, never]) so TypeScript 7 (tsgo) resolves dot-path autocomplete on large JSON dictionaries without hitting TS2589 ("Type instantiation is excessively deep and possibly infinite").

import type { MessageAt, MessageKey, NamespaceKey } from "next-fast-i18n";
import type en from "./messages/en.json";

type AnyNamespace = NamespaceKey<typeof en>; // "nav" | "hero" | "calculator" | ...
type HeroKey = MessageKey<MessageAt<typeof en, "hero">>; // "title" | "subtitle" | ...

Deterministic CLDR formatting (zero React #418 hydration drift)

Minimal Alpine Linux Docker images often ship different ICU data than Chrome and Safari (such as narrow no-break spaces \u202f in French numbers or differing abbreviated month periods in German and French). Calling Intl.DateTimeFormat or Intl.NumberFormat during SSR and hydration triggers React #418 mismatches.

next-fast-i18n formats UTC dates and integer grouping with explicit CLDR tables (en, de, fr, it with fallback):

import { formatDateLong, formatDateMedium, formatInteger } from "next-fast-i18n";

formatDateMedium(new Date("2026-01-05T12:00:00Z"), "de"); // "05.01.2026"
formatDateMedium(new Date("2026-01-05T12:00:00Z"), "fr"); // "5 janv. 2026"
formatDateLong(new Date("2026-03-15T12:00:00Z"), "de"); // "15. März 2026"
formatInteger(1_234_567, "fr"); // "1\u202f234\u202f567"

Pair this with formatDetection: { telephone: false } in your root layout metadata so mobile Safari does not wrap numeric strings in <a> tags before hydration.


global-error.tsx and Turbopack JSON tree-shaking

Do not import messages/en.json, messages/de.json, or messages/fr.json inside app/global-error.tsx (even via a named import like import { Error } from "../messages/en.json"). Turbopack bundles the entire JSON module on named imports, adding hundreds of kilobytes of every locale dictionary to the global error boundary chunk.

Keep the ~10 error strings in a small standalone TypeScript constant (see examples/nextjs-app/app/global-error.tsx) and assert equality with messages/*.json#Error in tests if needed.


Migrating from next-intl

  1. Remove next-intl/plugin from next.config.ts.
  2. Replace createMiddleware / defineRouting with createLocaleProxy from next-fast-i18n/proxy in proxy.ts (or middleware.ts).
  3. Replace i18n/request.ts with createServerI18n in lib/i18n.ts and export getTranslations / getT, getLocale, setRequestLocale, and getClientMessages.
  4. Replace <NextIntlClientProvider messages={allMessages}> in your root layout with <I18nProvider messages={await getClientMessages(locale, ["nav", "locale"])}>, and wrap interactive islands with <I18nMessages messages={await getClientMessages(locale, ["islandNs"])}>.
  5. Replace createNavigation from next-intl/navigation with createNavigation from next-fast-i18n/client.
  6. Keep your existing JSON message files ({var} interpolation, {count, plural, =0 {...} one {# ...} other {# ...}}, and <tag>...</tag> rich text work as-is).

Runnable Next.js 16 example

See examples/nextjs-app/ for a standalone Next.js 16 App Router app (en, de, fr) with proxy.ts, Server Components using getT(), a scoped <I18nMessages> calculator, and no required env vars:

cd examples/nextjs-app
bun install
bun run dev

Credits

Extracted from AgenturScout and maintained by Magicspace.

License

MIT

探索相关项目

加载中…