1

I started to create an open source project several months ago, in my spare time, so I have frontend written in ReactJS and I connect to backend API trough webpack devServer like this:

proxy: {
  '/api/**': {
    target: 'http://localhost:3001/project/backend',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  }
}

and I can fetch my data using API like this:

fetchData () {
  window.fetch('/api/')
    .then(res => res.json())
    ...
}

Now I'm trying to deploy my project on a web hosting with real domain name instead of localhost:3001 and I really can't figure out how to configure my frontend to use an addres like http://api.domain-name.com for backend. I know that I can just write api.domain-name.com in my fetchData method, but I don't want to to hardcode that address, because I am planning this project to be used by other people, so, obviously, some of them, and even I, don't want want to put them in situation to change manually those lines of code where frontend is trying to reach backend. I expect that this can be done somehow with a configuration file, for example, where I can write something like HOST: 'api.domain-name.com' and after that to import that file in project and to use the HOST constant. Can someone help me with an advise?

tourniquet
  • 1,375
  • 2
  • 15
  • 19

1 Answers1

1

You should use ENV variables to do this

REACT_APP_API_HOST=example.com yarn run build

Passing environment-dependent variables in webpack

Safi Nettah
  • 1,160
  • 9
  • 15