# Use Ovok CMS with i18n

Canonical page: https://docs.ovok.com/cms/use-ovok-cms-with-i18n

Keep your app's UI text in the Ovok CMS and load it into [i18next](https://www.i18next.com) at start-up. Translators edit it in the Ovok Console, so a changed label or a new language needs no release.

## What you need [#what-you-need]

| You need | Detail |
| --- | --- |
| The CMS enabled | See [Enable the CMS](/cms#enable-the-cms). |
| Your tenant code | [Find it](/authentication#find-your-tenant-code). |
| Published `translations` documents | On the same Ovok API the app reads. See [tenants](/cms#tenants). |
| An SDK, optionally | `@ovok/core` 0.4.51 or later for the web, or `@ovok/native` 1.16.1 or later for mobile. The plain API works with any framework. |

The `translations` collection is **open** by default, so a signed-out screen such as sign-in loads its text with only the tenant code and no API key. An HTTP call without `tenant` gets `400`; the SDKs send the client's `tenantCode`.

## 1. Author the translations [#1-author-the-translations]

In the Console, create one `translations` document for each group of text, usually one per screen or feature.

<Recording name="ovok-console-cms-translations" alt="Adding a translations group with keys and a German value in the Console's CMS editor" />

| Field | What to put |
| --- | --- |
| `slug` | The group name, such as `sign-in`. No dots: a dotted slug would nest under a different path. |
| `strings` | One row per text. The `key` is the name, and the `value` is the text. |
| `value` | Plain text, written once per language. A key with dots, such as `errors.required`, nests under the group. A key that is also a prefix wins as a text: with `title` and `title.short`, the SDK keeps `title` and skips `title.short`. |
| `status` | `published`. A draft is not delivered and looks the same as a missing group. |

Write the English text first, then add each language you ship as a bare code such as `de`, `fr` or `it`. An untranslated string falls back to English **string by string**, so a half-translated group still works.

A group of yours replaces Ovok's shared group of the same `slug` **whole**. If you reuse a shared group's name, such as `sign-in`, add every key you use, not only the ones you want to change. See [shared content](/cms#shared-content).

## 2. Load them into i18next [#2-load-them-into-i18next]

<Tabs items={["HTTP, any framework","JavaScript SDK","React Native SDK"]} groupId="ovok-i18n" persist>
<Tab value="HTTP, any framework">

Read the translations from the API, build a tree, and add it to i18next as a resource bundle.

```bash
curl --get 'https://api.sandbox.ovok.com/v1/public/cms/collections/translations/items' \
  --data-urlencode 'tenant=big-health-company' \
  --data-urlencode 'locale=de' \
  --data-urlencode 'limit=50'
```

```json
{
  "docs": [
    {
      "slug": "sign-in",
      "title": "Sign-in screen",
      "status": "published",
      "strings": [
        { "key": "title", "value": "Anmelden" },
        { "key": "errors.required", "value": "Pflichtfeld" }
      ]
    }
  ],
  "totalDocs": 1,
  "hasNextPage": false
}
```

```ts
// The CMS has bare two-letter codes: de-DE reads as de, and anything that is not a two-letter language as en.
const toCmsLocale = (language: string) => {
  const primary = language.split(/[-_]/)[0].toLowerCase();
  return /^[a-z]{2}$/.test(primary) ? primary : 'en';
};

type Tree = { [key: string]: string | Tree };
const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']);

// Puts a text at a dotted path. The first text wins, and a text is never turned into a group.
function setText(root: Tree, path: string[], value: string) {
  let node = root;
  for (const part of path.slice(0, -1)) {
    if (FORBIDDEN.has(part)) return;
    const next = (node[part] ??= {});
    if (typeof next === 'string') return;
    node = next;
  }
  const last = path[path.length - 1];
  if (FORBIDDEN.has(last) || Object.hasOwn(node, last)) return;
  node[last] = value;
}

async function loadCmsTranslations(i18n: any, tenant: string, language: string) {
  const locale = toCmsLocale(language);
  const tree: Tree = {};

  for (let page = 1; page <= 20; page++) {
    const url = new URL('https://api.sandbox.ovok.com/v1/public/cms/collections/translations/items');
    url.search = new URLSearchParams({ tenant, locale, page: String(page), limit: '50' }).toString();
    const body = await (await fetch(url)).json();

    for (const group of body.docs) {
      for (const { key, value } of group.strings ?? []) {
        if (typeof value !== 'string' || !value) continue; // an empty text is not a translation
        setText(tree, [group.slug, ...String(key).split('.')], value);
      }
    }
    if (!body.hasNextPage) break;
  }

  // deep: merge into what is there. overwrite: false keeps the app's own strings.
  i18n.addResourceBundle(locale, 'translation', tree, true, false);
}
```

Call it at start-up, and again when the user changes language.

</Tab>
<Tab value="JavaScript SDK">

`ovok.cms.translations` loads the groups for a language as one tree. Load it with `useOvokQuery` and add it to i18next as a bundle.

```tsx
import i18n from 'i18next';
import * as React from 'react';
import { initReactI18next, useTranslation } from 'react-i18next';
import { useOvokQuery } from '@ovok/core/next/react';

i18n.use(initReactI18next).init({
  lng: 'de-DE',
  fallbackLng: 'en',
  resources: { en: { translation: { app: { name: 'Acme' } } } },
  react: { bindI18nStore: 'added' }, // re-render when a bundle is added
});

// The CMS has bare two-letter codes: de-DE reads as de, and anything that is not a two-letter language as en.
const toCmsLocale = (language: string) => {
  const primary = language.split(/[-_]/)[0].toLowerCase();
  return /^[a-z]{2}$/.test(primary) ? primary : 'en';
};

export function CmsTranslations() {
  const { i18n } = useTranslation();
  const locale = toCmsLocale(i18n.language);
  const { data } = useOvokQuery((ovok, signal) => ovok.cms.translations(locale, { signal }), {
    queryKey: ['cms-translations', locale],
  });

  React.useEffect(() => {
    if (data) i18n.addResourceBundle(locale, 'translation', data, true, false);
  }, [data, i18n, locale]);

  return null;
}
```

Render `<CmsTranslations />` inside your `OvokProvider`.

- **It reads as the client's tenant.** The `Ovok` client sends its `tenantCode`, so the read works before sign-in.
- **`locale` is an app language or a CMS language.** `de-DE` reads as `de`. Omitted, the CMS answers in its default language.
- **It reads every page of the collection** and caches nothing on the device.

`useOvokQuery` returns `{ data, loading, error, refetch }`. A change to another CMS language refetches, because the locale is in the query key; a change from `de-DE` to `de-CH` does not, because both read `de`.

</Tab>
<Tab value="React Native SDK">

`useCmsTranslations` loads the groups and merges them into the i18next instance your app already uses. Call it once, near the root.

```tsx
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { useCmsTranslations } from '@ovok/native';

i18n.use(initReactI18next).init({
  resources: { en: { translation: { app: { name: 'Acme' } } } },
  fallbackLng: 'en',
});

export function CmsTranslations() {
  useCmsTranslations();
  return null;
}
```

- **It merges for you.** The CMS text goes into the `translation` namespace under the CMS language, such as `de`. i18next resolves `de-DE` through `de`.
- **It reads as the client's tenant.** Render it inside `OvokProvider` with the `Ovok` client from `@ovok/native/next`; it works before sign-in, for example on the sign-in screen.
- **Use the same i18next instance as your app.** The SDK imports `i18next` itself, so there must be one.
- **A language change refetches**, and re-renders the screens without switching the language again.

</Tab>
</Tabs>

## Precedence [#precedence]

When the same key exists in several places, the first of these wins:

| Priority | Source |
| --- | --- |
| 1 | Your app's own i18next strings |
| 2 | The CMS |
| 3 | The SDK's built-in English text |

The native SDK ships English text for `auth`, `common`, `profile`, `register`, `reset-password`, `settings` and `sign-in`. A CMS group with the same name overrides it, and your app's own strings override both. In the HTTP and web examples above, `addResourceBundle(…, true, false)` gives the same order.

## Languages and fallback [#languages-and-fallback]

| Your app asks for | The CMS answers |
| --- | --- |
| `de` | German. |
| `de-DE`, through an SDK | German: the SDK reads it as `de`. |
| `de-DE`, raw `?locale=de-DE` | **English.** The CMS has no `de-DE`, and an unknown language answers in the default one. |
| `it`, raw `?locale=it` | Italian where you have written it, English for the rest. |
| `it`, through the JavaScript SDK | Italian where you have written it, English for the rest. |
| `it`, through the React Native SDK | **English.** The React Native SDK reads only `de`, `en`, `fr` and `es`; any other language is read as `en`. |
| A key with no German text | The English text for that key. |
| A group your tenant has not written | Ovok's shared group of that name, if there is one. |

Write a new language's text in the CMS before you add it to your app; until then the app shows English. With the React Native SDK, a language beyond `de`, `en`, `fr` and `es` needs the HTTP approach above. Send `de`, not `de-DE`, when you call the API yourself.

## Staleness and offline [#staleness-and-offline]

- **Edits show up within about a minute**, longer behind a CDN. See [caching](/cms#caching).
- **Nothing is stored on the device.** When the CMS cannot be reached, the app shows its own strings and the SDK's English, and the hook's `error` is set.
- **Removing a key does not remove its text on mobile.** A text the app already merged stays until the app restarts.

## This is not the project localisation API [#this-is-not-the-project-localisation-api]

Ovok's localisation API, under `/v1/localization/` and `/v1/locales`, stores strings in your project's data and needs a signed-in session. The hooks on this page read the CMS instead. The two have separate text, language lists and fallback rules, so do not mix them in one app.

## Related [#related]

- [List the items of a collection](/cms/list-collection-items)
- [CMS](/cms)
- [Authentication](/authentication)
