React is a very popular framework, which most of us use today. Sometimes we want to use environment variables in our application but we don't know how to go about it.
Environment variables are used to store sensitive information. In our React application we can have environment variables and also when deploying, environment variables can be found on the server.
THIS IS HOW TO USE ENVIRONMENT VARIABLES ON YOUR MACHINE
.env SETUP
To define permanent environment variables in our React application, we need to setup our .env file.
create a
.envfile in the root of your React applicationcreate custom environment variables beginning with
REACT_APP_just like the example below.
NOTE: it must start with
REACT_APP_
// ENV FILE
REACT_APP_API_KEY=abcdefgh
With this we are done setting our .env file, now we have to read this REACT_APP_API_KEY in our project.
READING .env FILES
In our react app, we have process.env available to us. So to read REACT_APP_API_KEY we do
process.env.REACT_APP_KEY
if we set process.env.REACT_APP_API_KEY to a variable and log it out
const apiKey = process.env.REACT_APP_API_KEY
console.log(apiKey)
//abcdefgh
With this in place, we now know how to read .env files. This won't work immediately if we try it, for it to work we have to do one last thing
RESTART YOUR DEVELOPMENT SERVER
If you miss to restart you dev server, it won't work. Also if you add or change anything in your .env file, for you to use it you have to restart your dev server.
That's it lads, tell me what you think in the comments section.
Top comments (0)