REACT -Define and access env variable from front-end

April 10, 2020

In your React.js app, you may need to define some environment variable depending on your application logic

You can define those variables in webpack.config.js file

You have the webpack.DefinePlugin({}) plug-in to do this

So if you want to define API_URL, you can do it in following way

plugins: [
        new webpack.ExternalsPlugin('commonjs', [
            'electron'
        ]),
        new webpack.DefinePlugin({
            'API_URL': JSON.stringify('http://127.0.0.1:8000/api/')
          })
    ]
};

If you want to access it through React Component you can do

<div> {API_URL} </div>