@docyrus/i18n
v0.2.0
Published
Internationalization provider for Docyrus apps. Provides `DocyrusI18nProvider` + `t()` function with API-based and static translation support, cookie-based locale persistence, and `{{variable}}` interpolation.
Keywords
Readme
@docyrus/i18n
Internationalization provider for Docyrus apps. Provides DocyrusI18nProvider + t() function with API-based and static translation support, cookie-based locale persistence, and {{variable}} interpolation.
Supports React, React Native, Vue, and SSR (Next.js Server Components) via separate entrypoints.
Features
- Translation Provider: Wrap your app with
DocyrusI18nProviderand uset()anywhere - API + Static Merge: Fetch translations from API (
GET /v1/tenant/translations) and/or provide static JSON - Cookie-based Locale: Persists locale in a cookie (
docyrus-locale), survives page reloads - Locale Switching:
setLocale('en')writes cookie + refetches translations automatically - Interpolation: Supports
{{name}},{name}, and{0}placeholder formats - SSR + CSR:
'use client'directive for Next.js; static translations available immediately (no loading flash) - Auth Integration: Accepts
RestApiClientfrom@docyrus/api-client(auto Authorization header) - Translate Values:
tv('translate.Active')for API response values with "translate." prefix - React Hooks:
useDocyrusI18n()(full context) anduseTranslation()(lightweight) - React Native:
useI18n()with graceful fallback (works without provider),DocyI18nProviderwith MMKV/AsyncStorage support - Vue Composables:
useDocyrusI18n()anduseTranslation()for Vue 3 - Framework-Agnostic Core:
I18nManagerclass for custom integrations - Pluggable Storage:
CookieStorageAdapter(web),MemoryStorageAdapter(SSR/testing), custom adapters (MMKV, AsyncStorage) - TypeScript: Full type definitions included
Installation
npm install @docyrus/i18n @docyrus/api-clientpnpm add @docyrus/i18n @docyrus/api-clientPeer Dependencies
@docyrus/api-client>= 0.0.9 (optional — needed for API-based translations)react>= 19.2.0 (optional — required for React/Next.js/React Native entrypoints)vue>= 3.5.0 (optional — required for Vue entrypoint)
Entrypoints
| Import Path | Description | Framework |
|-------------|-------------|-----------|
| @docyrus/i18n | React provider, hooks | React, Next.js |
| @docyrus/i18n/rn | React Native provider, hooks (graceful fallback) | React Native (Expo) |
| @docyrus/i18n/vue | Vue provider, composables | Vue 3 |
| @docyrus/i18n/core | Pure TypeScript core (no framework dependency) | Any |
Quick Start (React)
import { DocyrusI18nProvider, useTranslation, useDocyrusI18n } from '@docyrus/i18n';
import { useDocyrusClient } from '@docyrus/signin';
function App() {
const client = useDocyrusClient();
return (
<DocyrusI18nProvider
client={client}
staticTranslations={{ 'common.loading': 'Yükleniyor...' }}
>
<Dashboard />
</DocyrusI18nProvider>
);
}
function Dashboard() {
const { t, isLoading } = useTranslation();
if (isLoading) return <div>{t('common.loading')}</div>;
return <h1>{t('dashboard.title')}</h1>;
}Quick Start (Next.js SSR)
// app/layout.tsx (Server Component)
import { I18nClientProvider } from './i18n-client-provider';
async function getTranslations() {
const res = await fetch(`${API_URL}/v1/tenant/translations`, {
headers: { Authorization: `Bearer ${serverToken}` }
});
return res.json();
}
export default async function Layout({ children }: { children: React.ReactNode }) {
const { data: translations } = await getTranslations();
return (
<html>
<body>
<I18nClientProvider staticTranslations={translations}>
{children}
</I18nClientProvider>
</body>
</html>
);
}// components/i18n-client-provider.tsx (Client Component)
'use client';
import { DocyrusI18nProvider, type TranslationDictionary } from '@docyrus/i18n';
import { useDocyrusClient } from '@docyrus/signin';
export function I18nClientProvider({
children,
staticTranslations
}: {
children: React.ReactNode;
staticTranslations: TranslationDictionary;
}) {
const client = useDocyrusClient();
return (
<DocyrusI18nProvider
client={client}
staticTranslations={staticTranslations}
>
{children}
</DocyrusI18nProvider>
);
}Quick Start (Vue)
<!-- App.vue -->
<script setup lang="ts">
import { RouterView } from 'vue-router';
import { DocyrusI18nProvider } from '@docyrus/i18n/vue';
import { useDocyrusClient } from '@docyrus/signin/vue';
const client = useDocyrusClient();
</script>
<template>
<DocyrusI18nProvider :client="client">
<RouterView />
</DocyrusI18nProvider>
</template><!-- Dashboard.vue -->
<script setup lang="ts">
import { useDocyrusI18n } from '@docyrus/i18n/vue';
const { t, locale, setLocale, isLoading } = useDocyrusI18n();
</script>
<template>
<div v-if="isLoading">Loading...</div>
<div v-else>
<h1>{{ t('dashboard.title') }}</h1>
<select :value="locale" @change="setLocale(($event.target as HTMLSelectElement).value)">
<option value="tr">Turkce</option>
<option value="en">English</option>
</select>
</div>
</template>Quick Start (React Native)
import { DocyI18nProvider, useI18n, type SupportedLanguage } from '@docyrus/i18n/rn';
// Storage is optional — use any getString/setString compatible adapter:
// MMKV, AsyncStorage, expo-sqlite, or no storage at all (session-only)
import { MMKV } from 'react-native-mmkv';
const mmkv = new MMKV();
const storage = {
getString: (key: string) => mmkv.getString(key),
setString: (key: string, value: string) => mmkv.set(key, value)
};
// translations.json — nested format
const translations = {
en: { common: { save: 'Save', cancel: 'Cancel' } },
tr: { common: { save: 'Kaydet', cancel: 'İptal' } }
};
function App() {
return (
<DocyI18nProvider
defaultTranslations={translations}
defaultLanguage="tr"
storage={storage}
>
<Dashboard />
</DocyI18nProvider>
);
}
function Dashboard() {
const { t, tv, lang, setLanguage } = useI18n();
return (
<View>
<Text>{t('common.save', 'Save')}</Text>
<Text>{tv('translate.Active')}</Text>
<Button onPress={() => setLanguage('en')} title="English" />
</View>
);
}Key differences from React/Web entrypoint:
useI18n()works without a provider (graceful fallback — returns key or fallback string)DocyI18nProvideraccepts nested translations ({ en: { common: { save: "Save" } } })t('key', 'Fallback')— second argument is a fallback string (not params)lang/setLanguagealiases forlocale/setLocale- Storage uses
getString/setStringpattern — compatible with MMKV, AsyncStorage, expo-sqlite, or any custom adapter storageprop is optional — if not provided, language preference won't persist across sessions
Configuration
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| client | RestApiClient \| null | null | Pre-configured API client with auth tokens |
| getAccessToken | () => Promise<string \| null> | undefined | Alternative auth callback (for SSR or custom setups) |
| apiUrl | string | undefined | API base URL (required with getAccessToken) |
| translationsEndpoint | string | 'v1/tenant/translations' | API endpoint path |
| staticTranslations | Record<string, string> | {} | Pre-loaded translations (available immediately) |
| cookieKey | string | 'docyrus-locale' | Cookie name for locale persistence |
| mergeStrategy | 'api-first' \| 'static-first' | 'api-first' | How to merge static and API translations |
| fallback | 'key' \| 'empty' \| (key) => string | 'key' | What to return when a key is not found |
| disableApiFetch | boolean | false | Skip API fetch entirely (use only static translations) |
| userLanguageEndpoint | string \| false | 'v1/users/me' | PATCH endpoint to persist user language. Set false to disable |
Hooks / Composables
useDocyrusI18n() (React / Vue)
Full i18n context. Available in React (@docyrus/i18n) and Vue (@docyrus/i18n/vue). Throws if no provider.
const {
t, // (key, fallbackOrParams?) => string
tv, // (value) => string — translate "translate.Active" values
locale, // current locale string | null
setLocale, // (locale: string) => void — writes cookie + refetches
status, // 'loading' | 'ready' | 'error'
isLoading, // boolean
translations, // Record<string, string>
error, // Error | null
refetch // () => Promise<void>
} = useDocyrusI18n();useI18n() (React Native)
Full i18n context with graceful fallback. Works with or without provider. Use in shared library components.
import { useI18n } from '@docyrus/i18n/rn';
const {
t, // (key, fallbackOrParams?) => string
tv, // (value) => string
lang, // SupportedLanguage ('en' | 'tr')
locale, // alias for lang
setLanguage, // (lang: string) => void
setLocale, // alias for setLanguage
isLoading, // boolean
error, // Error | null
refetch, // () => Promise<void>
reloadTranslations // () => Promise<void>
} = useI18n();useTranslation()
Lightweight hook for components that only need t():
const { t, tv, isLoading } = useTranslation();Merge Strategy
'api-first'(default):{ ...static, ...api }— API translations override static. Use this when static translations are fallbacks.'static-first':{ ...api, ...static }— Static translations override API. Use this for hardcoded overrides.
Static translations are available immediately on mount (no loading flash). API translations are fetched asynchronously and merged in.
Locale Management
Web (React / Vue)
- On mount: read locale from storage (cookie by default). If not set, locale is
null. setLocale('en'): write to storage +PATCH users/me { language }+ refetch translations.- SSR: cookie can be read server-side via Next.js
cookies()API.
React Native
- On mount: read from MMKV/AsyncStorage via
storage.getString(storageKey). userLanguageprop syncs with user profile language (e.g., "tr_TR" → "tr").setLanguage('en'): write to storage + callonLanguageChangecallback.- Remote translations fetched via
fetchRemoteprop.
Translation Function
The t() function accepts two call signatures:
// Basic lookup (returns key if not found)
t('common.save') // "Kaydet" or "common.save"
// With fallback string (returns fallback if key not found)
t('common.save', 'Save') // "Kaydet" or "Save"
// With interpolation params
t('greeting', { name: 'Ali' }) // "Merhaba, {{name}}!" → "Merhaba, Ali!"Interpolation
Three placeholder formats are supported:
// Double-brace (static translations convention)
t('greeting', { name: 'Ali' }) // "Merhaba, {{name}}!" → "Merhaba, Ali!"
// Single-brace named (API convention)
t('ai.chat', { name: 'Docyrus' }) // "Talk to {name} AI" → "Talk to Docyrus AI"
// Single-brace positional (API convention)
t('add.new', { '0': 'User' }) // "Add New {0}" → "Add New User"Translate Values (tv)
For API responses containing translatable values:
tv('translate.Active') // → t('common.Active') → "Aktif"
tv('Regular text') // → "Regular text" (unchanged)API Response Format
The API endpoint (GET /v1/tenant/translations) must return:
{
"success": true,
"data": {
"Show Expand Detail Button": "Detayı Genişlet Butonunu Göster",
"Add New {0}": "Yeni {0} Ekle",
"Talk to {name} AI": "{name} AI ile Konuş"
}
}Translation keys are flat strings (not dot-notation). Values may contain {0} or {name} placeholders.
Core (Framework-Agnostic)
import { I18nManager, interpolate, CookieStorageAdapter, MemoryStorageAdapter } from '@docyrus/i18n/core';
const manager = new I18nManager({
staticTranslations: { 'hello': 'Merhaba, {{name}}!' }
});
manager.subscribe((state) => console.log(state.status, state.translations));
await manager.initialize();
console.log(manager.t('hello', { name: 'Ali' })); // "Merhaba, Ali!"Development
pnpm install
pnpm dev # Watch mode
pnpm build # Build ESM + dts
pnpm lint # ESLint
pnpm typecheck # ESLint + tsc --noEmitLicense
MIT
