133

I am new on react.js I have implemented one component in which I am fetching the data from server and use it like,

CallEnterprise:function(TenantId){


    fetchData('http://xxx.xxx.xx.xx:8090/Enterprises?TenantId='+TenantId+' &format=json').then(function(enterprises) 
    {
        EnterprisePerspectiveActions.getEnterprise(enterprises);
    }).catch(function()
    {
        alert("There was some issue in API Call please contact Admin");
        //ComponentAppDispatcher.handleViewAction({
        //    actionType: MetaItemConstants.RECEIVE_ERROR,
        //    error: 'There was a problem getting the enterprises'
        //});
    });
},

I want to store Url in configuration file so when I deployed this on Testing server or on Production I have to just change the url on config file not in js file but I don't know how to use configuration file in react.js

Can anyone please guide me how can I achieve this ?

3
  • 1
    Do you use webpack or some tool to compile the js code? Commented Jun 1, 2015 at 9:06
  • It would be common to send that value, set and read from an environment variable to the web page as a global value available within your JavaScript. Then, use it to fetch data. Commented Jun 1, 2015 at 10:41
  • 2
    @PetrBela : yes I am using webpack to build bundle.js but I am taking about configuration file like web.config in .net Commented Jun 2, 2015 at 6:23

5 Answers 5

145

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

For React:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

Not sure if it covers your use case but it's been working pretty well for us.

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

23 Comments

You're welcome. BTW we've since learned that it's better to use JSON to avoid syntax errors. I've updated the code accordingly.
this doesn't work for me, I get this error : [Error: Cannot find module 'Config'] when using require('Config')
Would you please share whole webpack.config or the application in github? Thanks
What if I want webpack not bundle seperate config file into output.bundle.js? If it would be a seperate from bundle, may I still require('Config')? Thanks
How did any of you get this to work? I do it exactly as suggested and I'm getting 'Cannot find module 'Config'', same as @amgohan.
|
93

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

7 Comments

just remember your variable name must start with REACT_APP_
I have an ASP.NET Core app created with React template, and all I did was add an empty file under 'ClientApp' folder and put REACT_APP_MYSETTING=value in it, then refer to it as process.env.REACT_APP_MYSETTING in my JSX code, and it worked. Thanks!
.env does not work to me at all in create-react-app project
You will have to restart your project on npm once you've added .env to your root directory
@Rob the point isn't that it's a secret, it's that it changes by environment. I have an application that deploys to 1200 servers in four data centers across the country, on up to 8 clusters per data center, and local API endpoints are applied on each cluster. You don't want to hard-code something like that...
|
2

You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so

REACT_APP_SERVER_PORT=8000

In your applications entry file your just call dotenv(); before accessing the keys like so

process.env.REACT_APP_SERVER_PORT

1 Comment

although I think you need to specify your keys starting with REACT_APP_
1

In case you have a .properties file or a .ini file

Actually in case if you have any file that has key value pairs like this:

someKey=someValue
someOtherKey=someOtherValue

You can import that into webpack by a npm module called properties-reader

I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.

  1. Import that from dependencies section in package.json

"properties-reader": "0.0.16"

  1. Import this module into webpack.config.js on top

const PropertiesReader = require('properties-reader');

  1. Read the properties file

const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;

  1. Import this constant as config

externals: { 'Config': JSON.stringify(appProperties) }

  1. Use it as the same way as mentioned in the accepted answer

var Config = require('Config') fetchData(Config.serverUrl + '/Enterprises/...')

1 Comment

Your step 2 about webpack.config.js, if one is using create-react-app then there is no webpack config (or it is hidden). How to proceed in that case?
0

So not exactly a configuration file but you can also add environment variables in the package.json start script.

Before:

  "scripts": {
    "start": "react-scripts start",
    ....
  },

After:

  "scripts": {
    "start": "REACT_APP_TEST_ENV_VAR=TEST_DATA react-scripts start",
    ...
  },

You can read these now using the process.env.REACT_APP_TEST_ENV_VAR in your react code.

In a somewhat similar fashion you can also just move that env variable/config param to the command npm start command line.

So again before to launch your react app via command line: npm start

After: REACT_APP_TEST_ENV_VAR=TEST_DATA npm start

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.