Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access environment variables inside React JS web app?

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?

like image 239
SeaWarrior404 Avatar asked Sep 19 '17 10:09

SeaWarrior404


People also ask

How do you access environment in React?

Method 1: Using npm scripts to set environment variables Let's add some environment variables with a --env flag in our scripts. We've added the --env. API_URL= part in both scripts. Now, run your npm run dev command, go to your React component and use the process.

Where are .env files stored in React?

So let's get started on how to use that in our react js project. Open your project root directory and create a . env file inside that directory.


1 Answers

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.

like image 57
arikanmstf Avatar answered Oct 19 '22 08:10

arikanmstf