Node.js examples
Examples using the built-in fetch API (Node 18+). No extra packages required.
Setup
Store your API key in the environment:
bash
export I18N_API_KEY="key_live_XXXX"Minimal helper
js
// i18n.js
const BASE_URL = 'https://sapi.i18nme.com'
async function apiFetch(path) {
const res = await fetch(`${BASE_URL}${path}`, {
headers: { 'X-API-Key': process.env.I18N_API_KEY }
})
if (!res.ok) {
throw new Error(`i18n API error ${res.status}: ${await res.text()}`)
}
return res.json()
}
export const manifest = () => apiFetch('/v1/cached/manifest')
export const translations = (lang) => apiFetch(`/v1/cached/translations/${lang}`)
export const translationGroup = (lang, g) => apiFetch(`/v1/cached/translations/${lang}/${g}`)
export const translationKey = (lang, g, k) => apiFetch(`/v1/cached/translations/${lang}/${g}/${k}`)Fetch all languages and their translations
js
import { manifest, translations } from './i18n.js'
const { languages } = await manifest()
const bundles = Object.fromEntries(
await Promise.all(
languages.map(async ({ code }) => [code, await translations(code)])
)
)
console.log(bundles)
// { en: { common: { welcome: 'Welcome' } }, pl: { common: { welcome: 'Witaj' } } }Next.js integration
tsx
// lib/i18n.ts
const BASE = 'https://sapi.i18nme.com'
export async function loadTranslations(locale: string) {
const res = await fetch(`${BASE}/v1/cached/translations/${locale}`, {
headers: { 'X-API-Key': process.env.I18N_API_KEY! },
next: { revalidate: 60 }, // ISR: revalidate every 60 s
})
if (!res.ok) return {}
return res.json() as Promise<Record<string, Record<string, string>>>
}tsx
// app/[locale]/page.tsx
import { loadTranslations } from '@/lib/i18n'
export default async function Page({ params }: { params: { locale: string } }) {
const t = await loadTranslations(params.locale)
return <h1>{t.common?.welcome}</h1>
}Rate limit handling with retry
js
async function fetchWithRetry(url, options, retries = 1) {
const res = await fetch(url, options)
if (res.status === 429 && retries > 0) {
const wait = parseInt(res.headers.get('Retry-After') || '5') * 1000
await new Promise(r => setTimeout(r, wait))
return fetchWithRetry(url, options, retries - 1)
}
return res
}