i18nextreact-i18nexti18next-http-backend

How to write missing translations to file?


in my React app I have i18n configured like this:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import HttpApi from 'i18next-http-backend';

i18n
  .use(HttpApi)  // load translation using http -> see /public/locales
  .use(initReactI18next)
  .init({
    lng: "en",
    debug: true,
    fallbackLng: "en",
    saveMissing: true,
    backend: { addPath: 'http://localhost:3000/public/locales/{{lng}}/{{ns}}.missing.json'},
    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

Now when I add new untranslated text to my app, be it {t("find_box")}, I can see in the browser console that a POST request is being issued to the addPath:

{
    "POST": {
        "scheme": "http",
        "host": "localhost:3000",
        "filename": "/public/locales/en/translation.missing.json"
    }
}

with the response body {"find_box": "find_box"}. The request returns a 200.

I understood the saveMissing feature that the untranslated entry would be added to the file at addPath. But that doesn't happen. The file at addPath exists and contains an empty object { }.

  1. Is my assumption about the saveMissing feature correct?
  2. Do I need a custom missingKeyHandler to write the content of the POST request to file?
  3. I locally run the React app via docker-compose, does that make a difference?

Solution

  • The only thing the i18next-http-backend does is that POST request... now you need to handle that on your server side... Set the addPath to a server route that listens for that post request and write that to a file or a db or wherever you like.

    Only the i18next-fs-backend will automatically generate a file... but since you're in browser context this will not work...

    for example you could combine this with i18next-http-middleware, like here: https://github.com/i18next/i18next-http-middleware/blob/master/example/basic/index.js#L78