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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With