Search code examples
reactjscustom-backendi18next-http-backend

React i18next loading translation files both from frontend (e.g. localhost :3000) and backend (e.g. localhost:5000)


I am making one react app which fetches data from backend and displays in the browser. For changing the language for static names (like in header, footer), it is changed if I set locales folder inside public folder, and creating all the json files for required language code.

Now, I want to load the translation files from the backend as well, because, the data fetched from the backend is always random, and backend will send the corresponding translation files.

I am so much of confused of how to achieve that.

I have been through lots of stackoverflow solutions, which suggest to use custom backend plugin. But, I am confused how to create the custom backend plugin.

here is the part of code of my i18next.js configuration :

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

i18n
.use(initReactI18next)
.use(Backend)
.init({
    ns:['common', 'translation'],
    defaultNS : 'common',
//still loads the translation files if I do not define below line (because it is in public folder in react app)
    backend: { loadPath: "/locales/{{lng}}/{{ns}}.json" }
});

From the above code, I am just able to load the translation files that is in the frontend. If I change the line "backend" as :

backend : { loadPath : "http://localhost:5000/locales/{{lng}}/{{ns}}.json"

It will load the translation files from backend server at localhost: 5000. But, the translation files located in the public folder in not loaded now.

Can anyone help with some example, how to load both paths so that the translation files from both frontend and backend works.


Solution

  • When you have both defined resources in your local project and backend translations, you're capable of using i18next-chained-backend library to support both. Refer the short example here.

    Reference: https://www.i18next.com/how-to/add-or-load-translations