Adding an .env file to React Project
Solution 1
4 steps
-
npm install dotenv --save
-
Next add the following line to your app.
require('dotenv').config()
-
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'
- Finally, add
.env
to your.gitignore
file so that Git ignores it and it never ends up on GitHub.
If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_
for it to work.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/
NOTE - Need to restart application after adding variable in .env file.
Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f
Solution 2
So I'm myself new to React and I found a way to do it.
This solution does not require any extra packages.
Step 1 ReactDocs
In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file
1.1 create Root/.env
#.env file
REACT_APP_SECRET_NAME=secretvaluehere123
Important notes it MUST start with REACT_APP_
1.2 Access ENV variable
#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>
handleFetchData() { // access in API call
fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
1.3 Build Env Issue
So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.
Solution 3
Today there is a simpler way to do that.
Just create the .env.local file in your root directory and set the variables there. In your case:
REACT_APP_API_KEY = 'my-secret-api-key'
Then you call it in your js file in the following way:
process.env.REACT_APP_API_KEY
React supports environment variables since [email protected] .You don't need external package to do that.
*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.
Files priority:
npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)
More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Solution 4
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
Create a .env
file
// .env
API_KEY='my secret api key'
Add it to webpack.config.js
file
// 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
Solution 5
Steps to use environment variables in a CREATE REACT APP (Without dotenv package)
-
Create a new file called
.env
in the root folder of the project (NOT inside src folder but one level up. Remember, it should be at the same level as package.json (THIS IS VERY IMPORTANT) -
Define your variables like so (Note that every variable you define should start with REACT_APP_)
Example :
.env file
REACT_APP_ACCESS_KEY=8Sh9ZLwZevicWC-f_lmHvvyMu44cg3yZBU
Note: You don't have to enclose the value in
"" or ''
-
Now you can use the variable in any of your components like so
const apiKey = process.env.REACT_APP_ACCESS_KEY
The name should match the key given in the
.env
file -
Now before you try this out, always remember to restart the local server. Once you run
npm start
it works. This step applies whenever you make changes to the.env
file. We generally forget this step so it might not work. -
Optionally, check if
.env
entry is present in.gitignore
file. If the entry of.env
exists in.gitignore
then your.env
file will not be pushed to github(This is the reason why we use.env
in the first place).
Related videos on Youtube
Biii
Updated on July 08, 2022Comments
-
Biii almost 2 years
I'm trying to hide my API Key for when I commit to github, and I've looked through the forum for guidance, especially the following post:
How do I hide API key in create-react-app?
I made the changes and restarted yarn. I'm not sure what I'm doing wrong––I added an
.env
file to the root of my project (I named itprocess.env
) and in the file I just putREACT_APP_API_KEY = 'my-secret-api-key'
.I'm thinking it might be the way I'm adding the key to my
fetch
in App.js, and I've tried multiple formats, including without using the template literal, but my project will still not compile.Any help is much appreciated.
performSearch = (query = 'germany') => { fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${REACT_APP_API_KEY}`) .then(response => response.json()) .then(responseData => { this.setState({ results: responseData.results, loading: false }); }) .catch(error => { console.log('Error fetching and parsing data', error); }); }
-
RIYAJ KHAN about 6 yearsinstead of
process.env
name it.env.local or .env.process
and keep it outside of src directory -
Biii about 6 yearsHi @RIYAJKHAN I've changed the file to .env.local and it's definitely outside the src directory, but I'm still getting REACT_APP_API_KEY is not defined :/
-
n00bAppDev over 5 yearsWhat fixed it for me was simply closing the terminal running my local dev server and re-running
npm run start
. -
JBallin over 5 yearsPossible duplicate of Using API keys in a react app
-
JBallin over 5 yearsYou can't hide secrets in a react app. See stackoverflow.com/a/46839021/4722345
-
Nishant Mehta almost 5 yearsDO NOT use this to store secrets. From the docs...
WARNING: Do not store any secrets (such as private API keys) in your React app! Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
-
Leomord almost 4 yearsYou need to setup a server and use authentication like JWT in order to hide it. Read this suggestion for more info.
-
-
vikash almost 6 yearsneed to restart application after adding variable in .env file .use "REACT_APP_" before variable name if you create react application using "create-react-app".
-
user2763557 about 5 years@tarzen chugh what if I am deploying my app to AWS for example. Since .env is part of gitignore, wouldn't it get ignored? how can i go about including it production?
-
Isaac Pak almost 5 yearsif you're using webpack-devserver you won't see changes until you restart it.
-
ryanm almost 5 yearsIn my opinion, this is the correct answer! No additional packages necessary, and the proper React way to import environment variables. Other ways will work, but why add a package and code configuration when this is already done for you? Great answer!
-
rotimi-best over 4 yearsI was missing this
REACT_APP_
thank you. No other person mentioned it. -
Si8 over 4 yearsThis didn't work for me for some reason. I get
undefined
-
T04435 over 4 years@Si8 could you expand on you error/process. Which step you got
undefined
, did you restarted the app after adding a new variable to .env see 1.3 -
Kannan T over 4 years@T04435 thanks for this answer mate worked like charm
REACT_APP_
is the key here. Also how can i configure for different servers i have dev/beta/production do i need to have different env files for each server? -
T04435 over 4 years@KannanT You will need
.env.[ENVIRONMENT]
-
Kannan T over 4 years@T04435 I already have mate what I was referring is do I need I have different.env files for each server?
-
T04435 over 4 years@KannanT I think each server should have it onw .env DEV server --> .env.development PROD server --> .env.produciton
-
Benyam Ephrem over 4 years@vikash This was it for me, small comment big impact
-
aqteifan about 4 yearswhere do I add
require('dotenv').config()
? which file? -
Tested about 4 years@aqteifan u don't need to add that snippet, but then .ENV files naming plays a vital role
-
Muhammad Adistya Azhar about 4 years@user2763557 the pattern I use is create a
.env.example
file where the definitions of the env keys are laid out. Then, you can copy the.env.example
and create a.env
file (in development and production) containing you valid values e.g. keys, base urls etc. You have to add the.env
file to.gitignore
. -
naor.z about 4 yearsonly step 3 and 4 are relevant
-
kolexinfos almost 4 yearsYou need to restart your app, stop the running app and run npm start again
-
mgPePe almost 4 yearskeep in mind: all variables need to start with
REACT_APP_
to work. And also those variables are visible in the JS, so you should not put secret codes and private keys. -
Bobby Axe almost 4 yearsif your on
"react": "^16.13.1","react-dom": "^16.13.1","react-scripts": "3.4.1"
or higher and you you created the react application using"create-react-app"
command then you don't need to install the dot env package anymore create a.env
file out side your src folder (better at the project root) then name your variables withREACT_APP_
as a prefix to the variable name eg:REACT_APP_YOUR_VARIABLE
else it won't show up when you call it with{process.env.REACT_APP_YOUR_VARIABLE}
-
ameyaraje almost 4 yearsHow do you differentiate between dev and prod environments when using just a single
.env
file? Im aware we need to create.env.development
and.env.prod
files, but how do we differentiate between them using your method? -
Fatema Tuz Zuhora almost 4 years@ameyaraje Basically, we ignore the
.env
file at our.gitignore
. So, at the deployment, we just copy the.env
file to our server and just change the BASE_URL and other necessary values. In this way, when it needs to deploy the latest code, we just pull from the git master and deploy it. We do not think about the.env
as we are ignoring it and set it in our server at the very beginning. Thanks! -
Jorge Mauricio over 3 yearsThis was the best solution for me. Thanks. One note: I´m using server side rendering, so I had to update both webpack files (client too).
-
PRADIP GORULE over 3 yearsI do the same thing but it shows undefined in console
-
Omnibyte over 3 yearsProper naming did the job for me. I used .env.dev and React fell back to .env as it was looking for .env.development
-
stephan over 3 yearsname the file ".env" and not "config.env" or anything. This fixed the 'undefined' for me.
-
vikramvi over 3 yearsprocess.env.REACT_APP_API_KEY is not giving value showing undefined. I did stop server and restarted with npm start
-
Fatema Tuz Zuhora over 3 years@vikramvi Do you put the value in a variable named same
REACT_APP_BASE_URL
in the .env file? -
vikramvi over 3 years@FatemaT.Zuhora it was my bad, I had put .env in child directory by mistaken instead of putting it under root directory
-
Fatema Tuz Zuhora over 3 years@vikramvi Glad to know you've fixed it.
-
Michale Rezene over 3 yearsI have tried everything.
process.env.REACT_APP_API_KEY
saysundefined
. -
anonym over 3 yearsIf you are getting the values as undefined, recompile again.
-
Linas M. over 3 years@Aminu Kano could you please explain me what's the point of using this approach if the api-key is still visible if I view the bundle.js file online in sources?
-
Aminu Kano over 3 years@LinasM. yeah sure, but what do you mean by "online"?
-
Linas M. over 3 yearsWell, maybe I formulated my question in a not very precise way. I mean I set up all this process.env.API_KEY in my application and everything works fine on a localhost and if I push changes to the gitHub, the api key is not visible. But if I push my application to Heroku, it doesn't work, because Heroku cannot see the api key. So, I had to to undo all the changes in order for an application to work. So I don't see the benefits how can I make use of this approach
-
Aminu Kano over 3 years@LinasM. Okay I understand what you mean, the bundle.js is created when you generate the production build, and the API-key should definitely be visible in it. The benefit here is that you can share the source via "GitHub" without exposing the secret keys, and the generated and gitignored production build deployed to "Heroku". Let me know if this helps.
-
Linas M. over 3 years@AminuKano, Yes, that explained the point very clearly. Thank you
-
Sanat Gupta over 3 yearsafter recompile still getting undefined.
console.log('process', process.env.REACT_APP_BASE_URL);
-
kd12345 about 3 years@AdisAzhar Hi so i currently have a .env and .env.example . .env currently has all my keys and values and .env.example has my keys only. when i upload the file on AWS how do i remove the .example from the file name to make it .env only so i can be read by the other files?
-
Muhammad Adistya Azhar about 3 years@kd12345 is it a VM? Can you SSH into it and copy/ rename the file?
-
kd12345 about 3 years@AdisAzhar What do you mean by VM?
-
Muhammad Adistya Azhar about 3 years@kd12345 virtual machine
-
kd12345 about 3 years@AdisAzhar i dont want to give you an wrong answer but i dont know.
-
Muhammad Adistya Azhar about 3 years@kd12345 Amazon EC2?
-
kd12345 about 3 years@AdisAzhar yeahh
-
SajithK about 3 years<title>%REACT_APP_WEBSITE_NAME%</title> only works in build time.
-
randomuser about 3 years@Michale did you solve this issue? I also tried everything here and I'm still getting undefined
-
bluenote10 about 3 yearsI don't understand how this answer can have so many upvotes. The secret will be embedded into the build in plain text! See the big warning in the docs. Therefore step 4 is deluding: If you share your secret publicly in the build anyway, gitignoring the
.env
doesn't help that much. I'm wondering how many React apps in the wild already expose private keys... -
Michale Rezene about 3 yearsunfortunately, I didn't solve this issue. I tried it on another project too. I used create-react-app I don't know if that is the problem or not. I will post it if I found the answer. I will definitely get back to you. you do the same too
-
DanyMartinez_ about 3 yearsThanks! for help me!
-
rawand deheliah about 3 yearsis there a way to make this work , while .env file is outside the react app directory? , for example I have frontend dir , and backend dir, and I placed .env in the main dir , can react access that ?
-
Vansh Bhardwaj about 3 yearseasiest and best!
-
Maverick almost 3 yearsI lost a day trying to find out why react couldn't read my environmental variable inside an .env file, that it didn't started with the prefix "REACT_APP_". Why this shitty restriction? I would never imagine that. Even an explicit call to dotenv module don't work and returns with error. I just found why with this post, thanx
-
Shuhad zaman almost 3 yearsMake sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
-
The Muffin Man almost 3 yearsSo you spend the time to create this nice list of steps, but don't actually reveal how to use different environments. Considering we want to use one environment when testing locally vs making a production build. What are the file names? Will it just work or do you have to use a cmd line flag?
-
Yohan W. Dunon almost 3 yearsIs this method works for non create-react-app projects? Because I've created a react app from scratch using webpack and this is not working.
-
Hamidreza Ghanbari over 2 yearsand one tip is restart server to work well
-
Paul Maurer about 2 years
.env
file needs to be in UTF-8 format -
yaach about 2 years"Make sure you the .env in your root folder"....please make sure. Thanks!
-
Pan Vi about 2 yearsalso do not use any quotes or spaces in the variable definition REACT_APP_GOOGLE_MAP_API_KEY=qweqwew88754
-
Anupam Hayat Shawon about 2 yearsI think restarting the project app is necessary after following this process.
-
Sandeep Amarnath about 2 yearsYeah good point. I've mentioned in last but one bullet!
-
philipjc almost 2 yearsHow did this get the top answer when the example uses require in a client app? JS imports would be better.??