Illyism/next-fast-i18n
Tentang
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.
Pengembangan web dan aplikasiPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- Mengumpulkan riwayat
- dalam 15 hari
- Mengumpulkan riwayat
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
Aslinext-fast-i18n
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.

- 17.5x to 27.6x faster rendering than
next-intleven with AOT precompilation (29x to 37x faster vsnext-intldefaults; 17.5x faster in end-to-end React 19renderToStringSSR across 10 languages) - Full ICU MessageFormat parity by default across all locales (
{var}, 6-form CLDR plurals via nativeIntl.PluralRules+=N+offset:N,select,selectordinal, inlinenumber/date/time+ skeletons, ICU apostrophe escaping, nestedt.rich()/t.markup(),t.raw(), andcreateFormatterwithrelativeTime/list/dateTimeRange) - Opt-in
/litesubpath (next-fast-i18n/lite) for ultra-small bundles (2.66 KBgz provider + hooks,4.05 KBgz full app with nav + deterministic CLDR formatter: 2x smaller than precompilednext-intl) - Smaller client JS even with full ICU vs precompiled
next-intl, with zeronext.configplugin (5.16 KBvs5.23 KBgz for provider + hooks;7.10 KBvs7.92 KBgz withuseFormatter+ navigation;-58%to-84%vsnext-intldefaults) - 99% smaller RSC payload vs passing full dictionaries (
0.55 KBvs67.2 KB) via built-inpickMessages()and<I18nMessages>deep-merging (both libraries support manual slicing;next-fast-i18nincludes deep-merge islands out of the box) - Zero Alpine Docker
#418hydration drift with deterministic CLDR UTC date and integer formatters foren/de/fr/itand cachedIntlfallback for all other locales - Plain
308URL-only routing in Next.js 16proxy.ts(middleware.ts) with nonext.configplugin, no307cookie redirects, unconditionalx-localeanti-spoofing, and open-redirect guards - 0 runtime dependencies (
nextandreactare 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:
- 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. - Per-request SSR overhead: Re-parsing ICU syntax or re-creating per-render
Intlmemoizers on every SSR request added CPU time on pages with hundreds of translation calls. - Alpine Linux vs browser React
#418errors: Minimal Docker images ship different ICU data than Chrome and Safari (such as narrow no-break spaces\u202fin French numbers or abbreviated month periods in German and French), causing hydration mismatches on dates and grouped numbers. - Unexpected redirects and config plugins:
Accept-LanguageandNEXT_LOCALEcookie307redirects,Linkheader bloat, andnext-intl/pluginwrappers 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-intlmaintainer Jan Amann also opened amannn/next-intl#2553 to optimize hot-path plain strings and argument caching after seeing these benchmarks; once released,next-intlplain-string timings will improve (~2.5x faster than4.16.2).
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 aMapfor O(1) lookups. - Process-wide
LocaleCache+ SIMD scanning: Plain strings return straight from the map with zero parsing. Dynamic strings useindexOf("{")fast paths, compile once into compact tagged descriptors, and share lazily created nativeIntl.PluralRules/Intl.NumberFormat/Intl.DateTimeFormatinstances across SSR requests (avoiding per-render cache churn andJSON.stringifymemoization keys). - Prototype-safe resolution and merging:
resolvePath,pickMessages,mergeMessages, and ICUselectcases checkObject.hasOwn/Object.create(null)and ignore__proto__,constructor, andprototype. - Depth-bounded TypeScript 7 (
tsgo) types:MessageKey<T>andNamespaceKey<T>cap recursion at depth 6 (NextDepth = [1, 2, 3, 4, 5, never]) so large JSON dictionaries get autocomplete without hittingTS2589.
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 single308redirect to/or/pricing?tier=pro. - Unprefixed URLs (
/pricing) clonereq.nextUrl(req.nextUrl.clone()) for internal rewrites so Next.js standalone in Docker avoids redirect loops. x-localeis unconditionally overwritten on every forwarded request to block spoofed client headers.- Path boundaries are checked strictly so
/englishand/deutschare never stripped as/enor/de. - Protocol-relative paths (
/en//evil.comor//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
- Remove
next-intl/pluginfromnext.config.ts. - Replace
createMiddleware/defineRoutingwithcreateLocaleProxyfromnext-fast-i18n/proxyinproxy.ts(ormiddleware.ts). - Replace
i18n/request.tswithcreateServerI18ninlib/i18n.tsand exportgetTranslations/getT,getLocale,setRequestLocale, andgetClientMessages. - 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"])}>. - Replace
createNavigationfromnext-intl/navigationwithcreateNavigationfromnext-fast-i18n/client. - 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
Jelajahi proyek terkait
Memuat…