Search code examples
reactjsreact-i18next

React i18next Backend-Path different in local and production environment


I'm using a react app with react-i18next and loading the translation with i18next-xhr-backend

i18n
  .use(Backend) 
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    lng: "de",
    backend: {
      loadPath: '/static/locales/{{lng}}/{{ns}}.json'
    }        
  });

If I run it locally my app is served over http://localhost:3000/

and the translation file is also loading nicely (src is located in public/statuc/locales/ ) http://localhost:3000/static/locales/de/translation.json

I'm now facing the issue that in production the app is not served from root, instead the builded files are served over a subfolder. Because of that I changed my packages.json and added homepage

{
  "name": "myapp",
  "version": "0.1.0",
  "homepage": "/static/app/",
  ...
}

After building the application and deploying it on prod, it still loads correctly, but the translation files are not found.

http://production.tld/static/app/index.html

react app files are loaded correctly http://production.tld/static/app/static/js/main*.js

but the translation file is still fetched by http://production.tld/static/locales/de/translation.json which is not available anymore (instead http://production.tld/static/app/static/locales/de/translation.json would be correct)

I could fix it by changing the i18n config

 backend: {
     loadPath: '/static/app/static(locales/{{lng}}/{{ns}}.json'
 }  

then it works in production, but not locally anymore :-/

I'm not sure how to avoid this situation ?


Solution

  • You can pass loadPath as function.

    backend: {
      loadPath: () => {
        // check the domain
        const host = window.location.host;
        return (host === 'production.ltd' ? '/static/app':'') + '/static/app/static/locales/{{lng}}/{{ns}}.json';
      },
    },