I don't want to directly import security_access_key in my application due to security reason.
I tried accessing environment variable like below
step 1:
added security_access_key to .env file
security_access_key=abc123
step 2:
access it in App.js
console.log(process.env.security_access_key)
But getting value undefined.
Suggest any solution if anyone knows.
Thank in advance
If you are using create react app then you can use .env file in you root of you project.
Add a file like .env.development
inside add values like this
REACT_APP_SERVER_ENDPOINT=http://localhost:3000
make sure to add REACT_APP_
as the prefix. inside the application you can access it
process.env.REACT_APP_SERVER_ENDPOINT
4 simple steps to get it working
1) npm install dotenv --save
2) Next add the following line to your app.
require('dotenv').config()
3) Then create a .env file at the root directory of your application and add the variables to it.
//contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
4) Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.
Note:- You need to restart application after adding variable in .env file and use "REACT_APP_" before variable name if you are creating react application using "create-react-app".
if you are using create react app then use the solution recommended by TRomesh by adding REACT_APP_params, it is the recommended way by create react app https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables.
if you are using Webpack then you can use DefinePlugin to access that params
//webpack.config.js
new webpack.DefinePlugin({
'process.env.security_access_key': JSON.stringify(process.env.security_access_key),
}),
then you can access process.env.security_access_key from your react app