Lokesh Agrawal Lokesh Agrawal - 3 years ago 227
React JSX Question

Accessing backend server endpoint at runtime in React Application

I have a react application which gets served from ngnix server. This app hits an apache backend server to fetch data and use that data to create UI.

I configured two endpoints for my application, dev nginx and prod nginx. Now what I want is, when this application gets served from dev nginx server, then I want it to pick a dev endpoint of the backend tomcat server and when it gets served by prod nginx server I want it to pick the production tomcat server endpoint.

How can I inject this backend server endpoint in my react application.

Answer Source

You have many options. Here are a few of the simpler ones:

  1. Presumably you have at least one HTML file that is the landing page of your app. You can generate two sets of HTML files: one for dev, and one for production. Each set of HTML files would contain a JS variable indicating the environment.

  2. You can run a script before starting the nginx servers that modifies the HTML files and injects a variable (or, really, just the value of the variable) with environment information.

  3. If you don't want to modify the HTML file dynamically, you can create a simple JS file that just assigns a variable to the global scope with the environment information. Then your HTML file can load this (via a <script> tag) before loading the rest of your app.

  4. You can guess the Apache hostname based on the nginx hostname (e.g., via window.location.host).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download