1

I have a React application which works with a REST API that is deployed on the same machine as the React application.

  • The React application is deplyoed on port 80 (using Apache Http Server)
  • The REST API is a Flask based application deployed on port 5000.

Currently as a workaround I set the production server to run on host X.Y.W.Z so i hard-coded the API target in the React files:

const API_HOST = 'http://X.Y.W.Z:5000'

What is the best practice to set the API destination if i want it to be the same host as the React application but on a different port? (Saw some posts about it but no-one had a solution, here and here for example)

Maybe to forward the request from the React Router to the WebServer and set there a reverse proxy? How it can be configured?

On the development server i used the proxy attribute in the package.json (as here) to forward the request - but its on the specific development server and it still should be hardcoded.

(I think that the definition should be not depended on the deployed host (tomorrow i can change to host to different server - so i should always set the API target?)

2 Answers 2

0

Change API_HOST according to the node environment.

const API_HOST = process.env.NODE_ENV === 'production' ? 'http://X.Y.W.Z' : 'http://X.Y.W.Z:5000';.

And if you are using proxy for development server, then you can use specify the API_HOST as

const API_HOST = process.env.NODE_ENV === 'production' ? 'http://X.Y.W.Z' : '';

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm... it seems like it still hardcoding it, but in the package.json file. As i understand the webpack somehow inject the environment variable to the application on run time. Is there some kind of Hostname environment variable ? didn't find anything like this.
0
const API_HOST = process.env.NODE_ENV === 'production' ? 'http://X.Y.W.Z' : 
                                                         'http://X.Y.W.Z:5000';

And if you are using proxy for development server, then you can specify the API_HOST as:

const API_HOST = process.env.NODE_ENV === 'production' ? 'http://X.Y.W.Z' : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.