Search code examples
create-react-appreact-i18nexti18next-http-backend

Create React App - loading i18n translations from relative path


My React app loads from a relative path by setting the homepage variable in package.json. However i18next-http-backend still tries to load the translations from http://localhost:3000/locales/en/translation.json instead of http://localhost:3000/myapp/locales/en/translation.json. I even tried setting the loadPath option (not sure of the syntax though), but that didn't work. Please see below:

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json`,

    interpolation: {
      escapeValue: false // not needed for react as it escapes by default
    }
  })

How can I make this work?


Solution

  • The loadPath needs to be set as part of the initialisation of the Backend, so you need to do the following...

    i18n
      .use(Backend)
      .use(initReactI18next)
      .init({
        fallbackLng: 'en',
        debug: true,
        backend: {
            loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json`,
        }
        interpolation: {
          escapeValue: false // not needed for react as it escapes by default
        }
      })