BabelizeBabelize
SDK

Database content

Translate database rows and API responses on your server with @babelize/sdk/server: your own LLM key or Babelize credits, cached per text, no extra tables.

Your UI strings live in code and are translated at build time. Content from your database (product names, descriptions, articles, menus) is different: it changes all the time and there is far too much of it to put in locale files.

@babelize/sdk/server translates that content on your server, as it leaves your API:

App ──(Accept-Language: ja)──▶ your API ──▶ your database (one language)
                                   │
                                   └─▶ content.translate(rows, req) ──▶ cache ──miss──▶ LLM
  • Your content tables don't change. Your database keeps one language. Translations live in a cache: in memory, Redis, or one key/value table in your own Postgres or Supabase.
  • Your LLM or ours. Use your own OpenAI, Anthropic, Gemini, Groq or OpenRouter key, any OpenAI-compatible API, or Babelize credits.
  • Each text is translated once per language. The cache key is a hash of the exact text, so repeat reads cost nothing, and editing a row simply produces a new key.
  • Works for any client. React Native, web, iOS, Android: the app only sends its language.

Server only

@babelize/sdk/server holds your LLM or Babelize key. Run it in your backend (Node.js 18+), never in a browser or mobile app.

Set this up with AI

Copy a prompt for Claude Code, Cursor, Codex or any coding agent. It follows this page.

Install

npm install @babelize/sdk

1. Create a translator

Create one per process and reuse it.

lib/content.ts
import { createContentTranslator, providers } from '@babelize/sdk/server';

export const content = createContentTranslator({
  provider: providers.openai({ apiKey: process.env.OPENAI_API_KEY! }),
  locales: ['fr', 'de', 'ja', 'hi'],         // languages you support
  context: 'Food delivery app: restaurant names and menu items',
  doNotTranslate: ['Acme Eats'],             // brand names stay as written
});

2. Translate responses

Pass the rows and the request. The language comes from ?lang=, an X-Locale header or Accept-Language.

app.get('/menu', async (req, res) => {
  const items = await db.menuItems.findMany();
  res.json(await content.translate(items, req, { fields: ['name', 'description'] }));
});

translate() returns a translated copy (your rows are not modified). Requests in the source language, or in a language not in locales, get the data back unchanged.

3. Send the language from the app

React Native
import { getLocales } from 'expo-localization';

fetch(`${API_URL}/menu`, {
  headers: { 'Accept-Language': getLocales()[0]?.languageTag ?? 'en' },
});

Already using the Babelize SDK in the app? Send babelize.getLocale(), so content follows the language picked in your UI.

4. Translate on write (no wait on read)

A text that isn't cached yet is translated on the first request for it, which takes as long as the model does. To make every read a cache hit, translate when content is created or edited:

app.post('/menu', async (req, res) => {
  const item = await db.menuItems.create({ data: req.body });
  content.warmInBackground(item, { fields: ['name', 'description'] });   // every language in `locales`
  res.json(item);
});

warmInBackground() returns at once, so saving isn't slowed down by the model; failures go to onError and are retried on the next read. Use await content.warm(...) instead when you want to wait: it returns { cached, translated, failed } and never throws. On shutdown (or in tests), await content.drain() waits for background jobs.

5. Translate existing data

backfill() takes rows from an array, a generator or an async iterator over your database, and translates them page by page. Run it as a one-off script. Start with a dry run to see what it would cost:

scripts/backfill.ts
async function* allMenuItems() {
  for (let page = 0; ; page++) {
    const rows = await db.menuItems.findMany({ skip: page * 500, take: 500 });
    if (rows.length === 0) return;
    yield rows;
  }
}

const plan = await content.backfill(allMenuItems(), { fields: ['name', 'description'], dryRun: true });
console.log(plan);  // { rows: 5000, toTranslate: 40000, characters: 1900000, estimate: { usd: 9.4, … }, … }

await content.backfill(allMenuItems(), {
  fields: ['name', 'description'],
  onProgress: (p) => console.log(`${p.rows} rows`),
});

Cached texts are skipped, so a run that stops halfway resumes where it left off. Dry-run cost is an estimate: in USD for your own key (known for each vendor's default model only), in credits for providers.babelize. With the in-memory cache, the translations only last as long as the script's process, so backfill into Redis (or the cache your API uses).

Choosing fields

content.translate(post, req, { fields: ['title', 'body', 'comments.text'] });

Short text is ambiguous ("Orange": a colour or a fruit? "Light": weight or roast?). Pass an object to say what each field is; the model gets the description with the text:

content.translate(products, req, {
  fields: { name: 'coffee product name', roast: 'coffee roast level', description: '' },
});
  • Paths use dots. Arrays are transparent: comments.text covers every comment.
  • * matches any key: translations.*.label.
  • A path naming an object covers the text under it, skipping ids, URLs and codes.
  • skip excludes paths: { skip: ['author.name'] }.

User-written content

Posts, comments, bios and messages are usually shown as written. Always list fields for data that mixes your content with your users', for example a feed:

// Translate the labels around posts, never the posts themselves.
res.json(await content.translate(feed, req, { fields: ['badge', 'sponsorLabel', 'suggestion.reason'] }));

Without fields, every string that reads like text is translated, and ids, URLs, emails, dates, colours, enum values (ORDER_PLACED) and identifier keys (id, userId, slug, imageUrl, createdAt, …) are skipped. Listing fields is more predictable; prefer it for production.

Plain arrays and objects are copied and translated. Dates, Buffers and class instances are left as is, so convert ORM documents first (for example Mongoose .toObject() or .lean()).

Providers

import { providers } from '@babelize/sdk/server';

providers.openai({ apiKey, model? })
providers.anthropic({ apiKey, model? })
providers.gemini({ apiKey, model? })
providers.groq({ apiKey, model? })
providers.openrouter({ apiKey, model? })
providers.openaiCompatible({ baseUrl, apiKey, model })   // Azure OpenAI, Mistral, DeepSeek, Ollama, LiteLLM…
providers.babelize({ apiKey })                           // Babelize credits, bblz_sk_… key

With your own key, you pay your LLM vendor directly and no Babelize credits are used. With providers.babelize, each text in each language costs one translation unit (up to 500 characters), the same as the hosted /v1/translate/batch API.

Any object with a translate({ texts, sourceLocale, targetLocale, context, glossary }) method returning one string (or null) per text works as a provider, so you can use DeepL, Google Translate or your own model.

Caching

The default cache is in memory (50 000 texts): fast, but empty after every restart or deploy, and not shared between servers. In production, keep translations somewhere durable.

In your Postgres or Supabase (no Redis)

One key/value table, babelize_translations, holds every translation. Your content tables don't change.

import { Pool } from 'pg';
import { createContentTranslator, postgresCache, providers } from '@babelize/sdk/server';

const content = createContentTranslator({
  provider: providers.anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! }),
  cache: postgresCache(new Pool({ connectionString: process.env.DATABASE_URL })),  // creates the table on first use
  locales: ['fr', 'de', 'ja'],
});

With supabase-js instead, create the table once in the SQL editor (translationCacheTableSql() prints this) and pass a service role client, on the server only:

create table if not exists babelize_translations (
  key text primary key,
  value text not null,
  updated_at timestamptz not null default now()
);
-- Server-side only: no policies, so only the service role (your backend) can read or write it.
alter table babelize_translations enable row level security;
import { createClient } from '@supabase/supabase-js';
import { supabaseCache } from '@babelize/sdk/server';

const cache = supabaseCache(createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!));

In Redis

import Redis from 'ioredis';
import { createContentTranslator, providers, redisCache } from '@babelize/sdk/server';

const content = createContentTranslator({
  provider: providers.anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! }),
  cache: redisCache(new Redis(process.env.REDIS_URL!)),   // ioredis or node-redis v4+
  locales: ['fr', 'de', 'ja'],
});

Any object with getMany(keys) and setMany(entries) works as a cache (Memcached, a key-value store, your own table).

Keys include the text, the source and target language, context and the glossary. Changing any of them translates again; changing the model does not.

Screens that read the database directly

If parts of your app query the database themselves (Supabase, Firebase) instead of calling your API, translate those rows through one endpoint on your server. The queries stay as they are; your server keeps the LLM key and the cache.

Your server (Express)
app.post('/translate-content', express.json({ limit: '512kb' }), content.handler({
  collections: {
    gyms: ['name', 'description'],
    classes: { title: 'fitness class name', summary: '' },
  },
  authorize: (req) => verifySupabaseJwt(req.headers.authorization),   // only your signed-in users
}));
Your app (React Native or web)
import { createContentClient, useTranslatedContent } from '@babelize/sdk/react';

export const contentClient = createContentClient({
  url: `${API_URL}/translate-content`,
  locale: () => i18n.language,
  headers: async () => ({ Authorization: `Bearer ${(await supabase.auth.getSession()).data.session?.access_token}` }),
});

function GymList() {
  const { data } = useQuery({ queryKey: ['gyms'], queryFn: () => supabase.from('gyms').select('*') });
  const { items: gyms } = useTranslatedContent(contentClient, 'gyms', data?.data, { locale: i18n.language });
  // …render gyms
}
  • Only the collections and fields you list are translated; other fields come back unchanged and unknown collections get 404. Nobody can use the endpoint to translate arbitrary text on your bill.
  • The rows show as they are right away, then translated (from the cache: about 1 ms on the server plus the network). On any error they stay as they were.
  • text: true also allows { "text": "…" } for a See translation button on user posts; pair it with useTranslatedText(contentClient, post.text, { enabled: showTranslation }). Keep authorize on.
  • Next.js route handlers, Hono, Supabase Edge Functions: export const POST = content.fetchHandler({ … }).
  • Limits: 200 items and 512 KB per request by default (maxItems, maxBodyBytes).

Fixing a translation

When the model gets something wrong, set the right translation. In code, with overrides (versioned with your app):

createContentTranslator({
  // …
  overrides: { fr: { 'Light roast': 'Torréfaction légère' } },
});

Or at runtime, for example from an admin screen:

await content.override('Light roast', 'fr', 'Torréfaction légère');

override() is stored in the cache, so use Redis (or another persistent cache) for it to last. Overrides apply to the whole text, in every field, and are not affected by changes to context or the glossary.

Turning it off

enabled: false is a kill switch: translate() returns your data exactly as it came in, and neither the provider nor the cache is called, as if the SDK weren't installed. No provider is needed while it's off.

const content = createContentTranslator({
  enabled: process.env.TRANSLATE_CONTENT !== 'off',
  provider: providers.openai({ apiKey: process.env.OPENAI_API_KEY! }),
  locales: ['fr', 'de', 'ja'],
});

content.setEnabled(false);   // at runtime, e.g. from an admin switch or a feature flag
content.isEnabled();         // false

warm(), warmInBackground() and backfill() do nothing while it's off. The cache is kept, so turning it back on serves earlier translations at once. To remove the SDK completely, unwrap the translate() calls and uninstall it: your database was never changed. See Leaving Babelize.

Latency

SituationAdded latency
Cached (after warm() or an earlier read)a cache read: ~0 ms in memory, ~1 ms in Redis
Not cached, onMiss: 'wait' (default)up to timeoutMs (8 s): one model call
Not cached, onMiss: 'source'none: source text now, translated for the next request

When timeoutMs runs out, the untranslated text is returned and the translation keeps going in the background, so the next request gets it. A provider error never fails your request: the text comes back in the source language and onError is called.

Options

createContentTranslator({
  provider,                 // required
  sourceLocale: 'en',       // language of your content
  locales: ['fr', 'ja'],    // supported languages; others get the source text
  cache: memoryCache(),     // or redisCache(client), or your own
  context: '…',             // what the content is
  doNotTranslate: ['Acme'], // kept as written in every language
  glossary: { fr: { Cart: 'Panier' } },
  overrides: { fr: { 'Light roast': 'Torréfaction légère' } },
  enabled: true,            // kill switch: false returns data unchanged
  timeoutMs: 8000,          // longest wait for uncached text
  onMiss: 'wait',           // or 'source'
  concurrency: 4,           // provider calls in flight
  onError: (err) => log.warn(err),
});

translate() also takes fields, skip, context, timeoutMs and onMiss per call. Other methods: warm(), warmInBackground(), drain(), backfill(), override(), setEnabled(), isEnabled(). translateText(text, locale) translates one string, and resolveLocale(req) tells you which language a request will get.

What gets protected

The model is told to keep HTML tags, Markdown, URLs, emails, @mentions, #hashtags, emoji, numbers and placeholders ({name}, {{name}}, %s). A translation that loses a {placeholder}, %s or URL is rejected, and the source text is shown instead. Texts longer than the provider's limit are split at paragraphs and sentences, then joined back together.

Last updated: 2026-11-30

How is this guide?

On this page