2

I'm running both the front-end (React) and back-end (nodejs) on the same linux server.

In my front-end, I have a fetch request to the back-end which I have to specify as fetch('http://10.25.248.238:3001/'), the IP (local because this site is for internal company use) and port of the back-end.

Is there a way to avoid hardcoding this back-end IP address so that it still works if both the front-end and back-end gets moved to another server?

I have tried http://localhost:3001 but that actually tries to fetch from the localhost of the visitors of the website. fetch('/') didn't work either.

Registering a domain name is not appropriate as this site is only meant for internal use.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Avery235
  • 4,756
  • 12
  • 49
  • 83
  • When you say "front-end and back-end gets moved to another server" do you mean they will always be on the same machine or that the backend will be moved to one machine and the front to another? – Mark Jul 17 '17 at 07:14
  • 1
    Both the front-end and back-end will always be on the same machine. – Avery235 Jul 17 '17 at 07:37

1 Answers1

2

An easy solution is to define the environment variables in your Webpack settings and pass it into the React app.

You can create dev.webpack.config.js and prod.webpack.config.js and in each of the config file, use webpack.DefinePlugin:

new webpack.DefinePlugin({
   BASE_URL: 'YOUR_SERVER_BASE_URL'
});

And in your React App you can refer them with process.env.BASE_URL. For example:

let url = process.env.BASE_URL + '/user';
MattYao
  • 2,495
  • 15
  • 21
  • Where should I put these 2 files? What else do I have to do? Not familiar with webpack, i used `create-react-app`. – Avery235 Jul 17 '17 at 08:11
  • It seems Facebook team doesn't provide much freedom for developers to extend the current create-react-app. Check this post: https://github.com/facebookincubator/create-react-app/issues/99 I think the best way to create a React app is through a well-known yeoman generator or some good boilerplate examples so you have more control of the settings, environment etc. – MattYao Jul 18 '17 at 00:38
  • I'm just going to declare 2 variables and choose based on `process.env.NODE_ENV === "development"`. Still, the server url must be manually edited when both the front-end and back-end move to a new server. – Avery235 Aug 02 '17 at 01:58