What would be the process of setting up ENV variables to work in your react project when your react project isn't built using create-react-app, and has no backend?
3 Answers
Found the answer. Quoted from this post by Aminu Kano.
Webpack Users
If you are using webpack, you can install and use dotenv-webpack plugin, to do that follow steps below:
Install the package
yarn add dotenv-webpack OR npm i dotenv-webpack
// .env API_KEY='my secret api key' Add it to webpack.config.js file
// webpack.config.js const Dotenv = require('dotenv-webpack');
// webpack.config.js const Dotenv = require('dotenv-webpack'); module.exports = { ... plugins: [ new Dotenv() ] ... };
Use it in your code as
process.env.API_KEY
For more information and configuration information, visit here

- 756
- 10
- 25
-
To be clear, by "setting up env variables", you meant how to load them from a file in your project? Also keep in mind that create-react-app only makes prefixed env vars (`REACT_APP_...`) available at runtime. You probably don't want every variable in your frontend bundle. – timotgl Dec 09 '19 at 07:56
-
Yes that's right. This app is just for my portfolio, and I don't intend to hook up a backend, so it's not imperative to hook up a backend just to fully obscure the data. Unlike my last project where I used create-react-app (which already had dotenv built in behind the scenes) I opted this time around to create the webpack config from scratch. Just wasn't sure how to set it up to get the same functionality I was used to i.e. loading the API keys from env files. – Robert C Dec 09 '19 at 08:52
Step 1:
yarn add dotenv-webpack
Step 2: on webpack.config.js file:
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
Last step: create .env file & put system variable in it:
URL=something.com

- 101
- 1
- 2
I think you can you a .bashrc file in linux to add any environment variable you want to use in the program.
Variable=<value>
you can just add variables and corresponding values and then you save and source the bashrc file using source abc.bashrc and then those variables will be available in the envrionment for the current terminal. You can use this file in any programming language where you can read the environment variables.

- 106
- 8