1

Hi i trying to supported multi lang in my app , but i must to access to the key by the response that get from express. i am used i18n in react and express to get from the backend the translation. like this is work for me:

t('en.translation.user')

but i want to do it like this:

t('user')

here is my code in the client:

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

i18n
    .use(Backend)
    .use(initReactI18next)
    .init({
        lng: "en",
        fallbackLng: "en",
        backend: {
                loadPath: "http://localhost:4000/locales/resources.json?lng={{lng}}&ns={{ns}}",
                addPath: "http://localhost:4000/locales/add/{{lng}}/{{ns}}",
                allowMultiLoading: false,
        },
        interpolation: {
            escapeValue: false, // react already safes from xss
        },

    });
export default i18n;

my server is like this:

const i18next = require('i18next');
const Backend = require('i18next-node-fs-backend');
const i18nextMiddleware = require('i18next-express-middleware');

const pathTranslationPublic = path.join(__dirname, '/src/locales');
i18next.use(Backend).init({
    preload: ['en',],
    lowerCaseLng: true,
    backend: {
        loadPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.json`,
        addPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.missing.json`,
        jsonIndent: 4,
    },
    load: 'all',
    lng: 'en',
    fallbackLng: 'en',
    debug: true,
    saveMissing: true,
    formatSeparator:'.'
});
app.use(
    i18nextMiddleware.handle(i18next, {
        removeLngFromUrl: false,
    }),
);
app.get(
    '/locales/resources.json',
    i18nextMiddleware.getResourcesHandler(i18next),
);

this is the response from the client:

{
    "en": {
        "translation": {
            "user": "hello user"
        }
    }
}
Guy 235
  • 21
  • 2

1 Answers1

0

getResourcesHandler is used for multiloading...

To provide the translations to your react client, just serve them statically, i.e.

app.use(express.static(pathTranslationPublic));

This way the client can have a loadPath like '/{{lng}}/{{ns}}.json'

btw: i18next-node-fs-backend is deprecated, use i18next-fs-backend instead i18next-express-middleware is deprecated, use i18next-http-middleware instead

For a react guide with i18next, have a look at: https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb

adrai
  • 2,495
  • 1
  • 15
  • 18
  • Ok thank you. but my problem is that the client will need the key of the lang and the key of the translations and after that i need to write the correct key that i want. if i has one more languge this: t('en.translation.user') not going to work. – Guy 235 Feb 10 '22 at 20:53
  • When serving the translations statically, like app.use(express.static(pathTranslationPublic)); the client can do this: t('user') – adrai Feb 10 '22 at 21:31