@pullwish/i18n
v1.1.1
Published
Translation management SDK for Pullwish — load, cache, and interpolate translations with automatic cache invalidation
Maintainers
Readme
@pullwish/i18n
Translation management SDK for JavaScript and TypeScript. Loads translation keys from your Pullwish project, caches them in localStorage and revalidates them against the server (content hash), and provides {{variable}} interpolation plus ICU plural forms. Works in the browser, Node.js, and React Server Components.
Installation
npm install @pullwish/i18nRequired API key permission: public:read
Quick Start
import { PullwishI18n } from "@pullwish/i18n";
const i18n = new PullwishI18n({
apiKey: "ft_live_your_api_key_here",
projectId: "your-project-id",
locale: "en",
fallbackLocale: "en",
});
await i18n.init();
i18n.t("nav.home"); // "Home"
i18n.t("greeting", "Hello", { name: "Ada" }); // "Hello, Ada!"
i18n.t("cart.items", undefined, { count: 3 }); // "You have 3 items"Configuration
I18nConfig
| Option | Type | Default | Description |
| ------------------- | ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------- |
| apiKey | string | required | API key with public:read permission |
| projectId | string | required | Your Pullwish project ID |
| locale | string | required | Active locale to load (e.g. "en", "nb", "de") |
| apiUrl | string | "https://www.pullwish.com" | Custom API base URL |
| fallbackLocale | string | — | Locale to use when a key is missing in the active locale |
| debug | boolean | false | Log cache hits, fetch results, and warnings to the console |
| initialData | Record<string, string> | — | Pre-loaded translations (SSR/RSC). When set, init() skips localStorage and network |
| namespace | string | — | Load only keys in this namespace to reduce payload size |
| reportMissingKeys | boolean | true | Send missing key telemetry to Pullwish. Missing keys appear in the dashboard's "Missing Keys" tab |
Methods
i18n.init(): Promise<void>
Load translations from the localStorage cache immediately, then validate against the server. The Pullwish API does not send ETag or 304 responses today (a CDN would strip the CORS headers), so revalidation downloads the locale again, served from the CDN cache for up to 15 minutes. When initialData is set (SSR mode), this is a no-op.
i18n.t(key, fallbackText?, vars?): string
Translate a key.
- Falls back to
fallbackLocalewhen the key is missing in the active locale. - Falls back to
fallbackTextwhen the key is missing everywhere. - Falls back to
keyitself as a last resort. varssupports{{variable}}interpolation.- When
vars.countis a number, resolves ICU plural forms in the translation value.
ICU plural syntax (store this in the Pullwish dashboard):
You have {count, plural, one {# item} other {# items}}i18n.setLocale(locale): Promise<void>
Switch to a different locale. Loads from cache first, then fetches from the server. Notifies all onChange listeners after the switch.
i18n.loadNamespace(ns): Promise<void>
Load an additional namespace of translations at runtime and merge them into the active store. Use this to load large namespaces (e.g. "admin") only when the user navigates to that section.
i18n.onChange(listener): () => void
Register a callback that fires whenever the locale or translations change. Returns an unsubscribe function. Use this in React to trigger re-renders without a full page reload.
i18n.getLocale(): string
Returns the currently active locale string.
i18n.isReady(): boolean
Returns true after init() has completed its first fetch.
i18n.preload(locale): Promise<void>
Warm the localStorage cache for a locale without switching to it. Useful for preloading the next locale before the user switches.
i18n.getKeys(): string[]
Returns all loaded translation keys for the current locale.
createServerI18n(config): Promise<ServerI18n>
Server-side helper for React Server Components and SSR. Fetches translations with a 5-minute Next.js revalidation window by default. Returns an object with t(), locale, and translations (pass as initialData to the client to avoid a second round-trip).
import { createServerI18n } from "@pullwish/i18n";
const i18n = await createServerI18n({
apiKey: process.env.PULLWISH_API_KEY!,
projectId: process.env.PULLWISH_PROJECT_ID!,
locale: params.locale,
});
// In a Server Component:
return <h1>{i18n.t("hero.title")}</h1>;
// Pass to Client Component to skip a second fetch:
return <ClientHero initialData={i18n.translations} />;Examples
Variable interpolation
// Translation in dashboard: "Hello, {{name}}! You have {{count}} messages."
i18n.t("dashboard.greeting", undefined, { name: "Ada", count: 5 });
// → "Hello, Ada! You have 5 messages."ICU plural forms
// Translation in dashboard: "{count, plural, one {# new message} other {# new messages}}"
i18n.t("inbox.count", undefined, { count: 1 }); // → "1 new message"
i18n.t("inbox.count", undefined, { count: 5 }); // → "5 new messages"Locale switching
await i18n.setLocale("nb");
console.log(i18n.getLocale()); // "nb"
i18n.t("nav.home"); // → "Hjem"Lazy-loading namespaces
const i18n = new PullwishI18n({
apiKey: "ft_live_...",
projectId: "proj-123",
locale: "en",
namespace: "common", // loads only "common" keys on init
});
await i18n.init();
// Later, when the user navigates to the admin section:
await i18n.loadNamespace("admin");
i18n.t("admin.users.title"); // now availableReact hook
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { PullwishI18n } from "@pullwish/i18n";
const i18n = new PullwishI18n({
apiKey: process.env.NEXT_PUBLIC_PULLWISH_API_KEY!,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID!,
locale: "en",
fallbackLocale: "en",
});
const I18nContext = createContext(i18n);
export function I18nProvider({
children,
locale = "en",
}: {
children: React.ReactNode;
locale?: string;
}) {
const [ready, setReady] = useState(false);
useEffect(() => {
i18n.setLocale(locale).then(() => setReady(true));
}, [locale]);
if (!ready) return null;
return <I18nContext.Provider value={i18n}>{children}</I18nContext.Provider>;
}
export function useTranslation() {
const i18n = useContext(I18nContext);
return { t: i18n.t.bind(i18n), locale: i18n.getLocale() };
}Next.js Server Component + client hydration
// app/[locale]/page.tsx (Server Component)
import { createServerI18n } from "@pullwish/i18n";
import { HeroClient } from "./hero-client";
export default async function Page({ params }: { params: { locale: string } }) {
const i18n = await createServerI18n({
apiKey: process.env.PULLWISH_API_KEY!,
projectId: process.env.PULLWISH_PROJECT_ID!,
locale: params.locale,
});
return (
<>
<h1>{i18n.t("hero.title")}</h1>
{/* Pass translations so the client component skips its own fetch */}
<HeroClient initialData={i18n.translations} locale={params.locale} />
</>
);
}
// hero-client.tsx ("use client")
import { PullwishI18n } from "@pullwish/i18n";
export function HeroClient({
initialData,
locale,
}: {
initialData: Record<string, string>;
locale: string;
}) {
const i18n = new PullwishI18n({
apiKey: process.env.NEXT_PUBLIC_PULLWISH_API_KEY!,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID!,
locale,
initialData, // no network call — uses server data
});
i18n.init();
return <p>{i18n.t("hero.subtitle")}</p>;
}Environment Support
| Environment | Supported | Notes |
| ----------------------- | --------- | ---------------------------------------------------- |
| Browser | ✅ | localStorage cache + hash revalidation |
| Node.js | ✅ | In-memory cache; no localStorage |
| React Server Components | ✅ | Use createServerI18n() |
| Edge / Workers | ✅ | Use createServerI18n() — no cache TTL revalidation |
Ships as CJS + ESM with TypeScript declarations.
Framework Integrations
React / Next.js App Router
// Server Component — app/[locale]/page.tsx
import { createServerI18n } from "@pullwish/i18n";
export default async function Page({ params }: { params: { locale: string } }) {
const i18n = await createServerI18n({
apiKey: process.env.PULLWISH_API_KEY!,
projectId: process.env.PULLWISH_PROJECT_ID!,
locale: params.locale,
});
return (
<>
<h1>{i18n.t("hero.title")}</h1>
{/* Pass to Client Component — no second network call */}
<ClientNav initialData={i18n.translations} locale={params.locale} />
</>
);
}React hook with locale switching
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { PullwishI18n } from "@pullwish/i18n";
const i18n = new PullwishI18n({ apiKey: "...", projectId: "...", locale: "en" });
const I18nContext = createContext(i18n);
export function I18nProvider({ children }: { children: React.ReactNode }) {
const [, rerender] = useState(0);
useEffect(() => {
void i18n.init();
return i18n.onChange(() => rerender((n) => n + 1));
}, []);
return <I18nContext.Provider value={i18n}>{children}</I18nContext.Provider>;
}
export function useTranslation() {
const i18n = useContext(I18nContext);
return { t: i18n.t.bind(i18n), locale: i18n.getLocale() };
}Debugging / Local Development
const i18n = new PullwishI18n({
apiKey: process.env.NEXT_PUBLIC_PULLWISH_API_KEY!,
projectId: process.env.NEXT_PUBLIC_PULLWISH_PROJECT_ID!,
locale: "en",
debug: true, // log cache hits, fetches, and warnings
reportMissingKeys: false, // disable telemetry during development
});
await i18n.init();
console.log(i18n.getKeys()); // inspect all loaded keys
console.log(i18n.isReady()); // true after init() completesTypeScript
All public types are exported from the package entry point:
import type {
I18nConfig, // Full constructor config
ServerI18n, // return type of createServerI18n()
} from "@pullwish/i18n";Named exports: PullwishI18n (class), createServerI18n (async factory).
