how to set react environment variable code example

Example 1: enviroment variable in react

WARNING: Do not store any secrets (such as private API keys) in your React
app! (source: https://create-react-app.dev/docs/adding-custom-environment-variables)
Reason: Environment variables are embedded into the build, meaning anyone can view them
by inspecting your app's files.

Unfortunately, keeping any key in your React client, even if you are using 
gitignore and an .env file, is not secure.

Solution: You should really only save API keys or secrets in your backend such 
as Node / Express. You can have your client send a request to your backend API,
which can then make the actual API call with the API key and send the data back
to your client.

Example 2: react environment variables

// Place a filer called .env at the doc root of your project
/*
my-react-app/ 
 |-node-modules/
 |-src/
 |-public/
 |-.env
 |-gitignore
 |-package.json
 |-package.lock.json.
 |-README.md
*/
// Edit the .env file and create your cusotm Environment Variables
// DO NOT USE SINGLE OR DOUBLE QUOTES!

REACT_APP_CLIENT_ID=jfjffffaddfeettgydgdffv
REACT_APP_KEY=aaddddawrfffvvvvssaa

// They will be READ-ONLY from your JS file, you can print them
// or assign them to other variables

console.log(process.env.REACT_APP_CLIENT_ID);
console.log(process.env.REACT_APP_KEY);

var id = process.env.REACT_APP_CLIENT_ID;
var key = process.env.REACT_APP_KEY;

Tags:

Misc Example