How to access environment variables inside React JS web app?

10,884

If you are using webpack, it is possible with Webpack Define plugin.

webpack.config.js:

    ...
    plugins: [
     new webpack.DefinePlugin({
       'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
     })
    ]      
    ...

and then simply you can use on your javascript file.

console.log(NODE_ENV);

edit: not alias, define plugin.

Share:
10,884
SeaWarrior404
Author by

SeaWarrior404

Updated on June 09, 2022

Comments

  • SeaWarrior404
    SeaWarrior404 almost 2 years

    I have an environment variable that I need to access inside my render method. Since its a custom ENV variable, I cannot use (process.env.NODE_ENV). I have read that React sanitises all process.env access.

    How to access my custom environment variable (CLUSTER_ENV) inside React web app?

  • Mariya James
    Mariya James over 6 years
    I am using react meteor application, I need to use these env varible in react component, I am having babel rather than webpack