1

I am very new to ReactJS and I might be thinking completely wrong. In our react app I make a lot of AJAX calls to the backend. For example, in dev I make calls to http://localhost:3000, in production I (naturally) use another host, which changes depending on the installation.

The hosts are static, set once and never change.

How do I make the host-information manageable in React?

I read about redux/flux etc to store global variable, but this is overkill for us. We just need to have one string (URL/host-info) that we can replace with another. We can store the info in a file, as a command-line param or whatever. We just need it to be simple.

UPDATE: Turn out that I fully did not understand the build system. As Dan pointed out we use webpack to package the solution. Using a loader we could swap out our configuration-settings in the code. We ended up using a simple string replacement loader (string-replace-webpack-plugin) since env variables are not suitable for this solution.

2
  • Are you doing any kind of bundling before pushing to production? Using browserify or webpack or anything like that? Commented Mar 18, 2016 at 16:43
  • Yes. We are using webpack, although I have not fully understood how it works. Commented Mar 18, 2016 at 18:08

1 Answer 1

2

What you're describing are usually known as environment variables. You generally maintain a specific set of environment variables for each context your application is developed or run in.

For instance you might have an APP_HOST environment variable which would be set differently at your local machine, than it would at your server.

Most programs that run on the server can read the environment variables directly, but because React apps run in the client's browser, you'll have to make them aware of the appropriate environment variables before they are served.

The easiest way to do this is with envify.

Envify will allow you to reference environment variables from your frontend code.

// app.js
const host = process.env.APP_HOST;
fetch(host);

Envify is a Browserify transform, meaning you'd need to run your code through a command like this.

# define some environment variables
APP_HOST="localhost:3000"
# build the code
browserify app.js -t envify -o bundle.js

What comes out the other side would be:

// bundle.js
var host = "localhost:3000";
fetch(host);

If you use Webpack, there's a similar alternative in the form of envify-loader.

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

1 Comment

Thank. Turns out I did not fully understand webpack. Using a string-replacer loader we could swap out our configuration-setting. In our case env. variables are not suitable, but if they where your solution would be perfect. (Basically the same but using a different loader)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.