211

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 it process.env) and in the file I just put REACT_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);
     });
}
Biii
  • 2,151
  • 3
  • 8
  • 8
  • instead of `process.env` name it `.env.local or .env.process ` and keep it outside of src directory – RIYAJ KHAN Mar 30 '18 at 17:56
  • 2
    Hi @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 :/ – Biii Mar 30 '18 at 18:07
  • 6
    What fixed it for me was simply closing the terminal running my local dev server and re-running `npm run start`. – n00bAppDev Oct 26 '18 at 04:12
  • Possible duplicate of [Using API keys in a react app](https://stackoverflow.com/questions/46838015/using-api-keys-in-a-react-app) – JBallin Nov 01 '18 at 19:54
  • 6
    You can't hide secrets in a react app. See stackoverflow.com/a/46839021/4722345 – JBallin Nov 01 '18 at 19:55
  • 15
    DO NOT use this to store secrets. From the [docs](https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables)...`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.` – Nishant Mehta Jun 19 '19 at 23:36
  • 3
    You need to setup a server and use authentication like JWT in order to hide it. Read [this suggestion](https://github.com/react-boilerplate/react-boilerplate/issues/1744#issuecomment-303112505) for more info. – Leomord Jun 12 '20 at 08:13

11 Answers11

287

4 steps

  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'
  1. 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

tarzen chugh
  • 8,821
  • 4
  • 17
  • 28
  • 68
    need to restart application after adding variable in .env file .use "REACT_APP_" before variable name if you create react application using "create-react-app". – vikash May 30 '18 at 06:30
  • 1
    @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? – user2763557 Mar 20 '19 at 13:30
  • @vikash This was it for me, small comment big impact – Benyam Ephrem Dec 20 '19 at 06:38
  • 7
    where do I add ```require('dotenv').config()```? which file? – aqteifan Feb 03 '20 at 20:38
  • 1
    @aqteifan u don't need to add that snippet, but then .ENV files naming plays a vital role – Tested Feb 27 '20 at 06:17
  • 3
    @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`. – Adis Azhar Mar 19 '20 at 17:02
  • only step 3 and 4 are relevant – naor.z Mar 30 '20 at 14:02
  • keep 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. – mgPePe May 21 '20 at 12:43
  • if 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 with `REACT_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}` – Bobby Axe Jun 20 '20 at 12:35
  • @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? – kd12345 Jan 21 '21 at 06:06
  • @kd12345 is it a VM? Can you SSH into it and copy/ rename the file? – Adis Azhar Jan 21 '21 at 10:18
  • @AdisAzhar What do you mean by VM? – kd12345 Jan 21 '21 at 11:33
  • @kd12345 virtual machine – Adis Azhar Jan 21 '21 at 11:34
  • @AdisAzhar i dont want to give you an wrong answer but i dont know. – kd12345 Jan 21 '21 at 11:36
  • @kd12345 Amazon EC2? – Adis Azhar Jan 21 '21 at 11:36
  • @AdisAzhar yeahh – kd12345 Jan 21 '21 at 11:37
  • %REACT_APP_WEBSITE_NAME% only works in build time. – SajithK Feb 05 '21 at 03:19
  • I 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.](https://create-react-app.dev/docs/adding-custom-environment-variables/.) 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... – bluenote10 Feb 24 '21 at 20:11
  • I 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 – Maverick Jun 09 '21 at 12:59
  • So 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? – The Muffin Man Jul 02 '21 at 06:51
  • `.env` file needs to be in UTF-8 format – Paul Maurer Jan 24 '22 at 22:21
  • How did this get the top answer when the example uses require in a client app? JS imports would be better.?? – philipjc May 18 '22 at 07:28
170

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.

T04435
  • 10,027
  • 3
  • 49
  • 51
  • 15
    In 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! – ryanm May 02 '19 at 18:21
  • 19
    I was missing this `REACT_APP_` thank you. No other person mentioned it. – rotimi-best Jul 25 '19 at 12:57
  • 4
    This didn't work for me for some reason. I get `undefined` – Si8 Sep 24 '19 at 14:30
  • @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 – T04435 Sep 25 '19 at 00:26
  • @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? – Kannan T Oct 15 '19 at 17:12
  • @KannanT You will need `.env.[ENVIRONMENT]` – T04435 Oct 15 '19 at 23:18
  • 1
    @T04435 I already have mate what I was referring is do I need I have different.env files for each server? – Kannan T Oct 16 '19 at 01:16
  • @KannanT I think each server should have it onw .env DEV server --> .env.development PROD server --> .env.produciton – T04435 Oct 16 '19 at 01:50
  • You need to restart your app, stop the running app and run npm start again – kolexinfos Apr 26 '20 at 13:58
  • name the file ".env" and not "config.env" or anything. This fixed the 'undefined' for me. – stephan Oct 01 '20 at 07:24
  • 7
    I have tried everything. `process.env.REACT_APP_API_KEY` says `undefined`. – Michale Rezene Oct 14 '20 at 20:42
  • @Michale did you solve this issue? I also tried everything here and I'm still getting undefined – randomuser Feb 24 '21 at 15:58
  • unfortunately, 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 – Michale Rezene Feb 24 '21 at 20:25
  • is 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 ? – rawand deheliah Mar 16 '21 at 09:45
  • Is 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. – Yohan W. Dunon Jul 10 '21 at 19:43
89

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 react-scripts@0.5.0 .You don't need external package to do that.

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env

*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

Sarah
  • 1,853
  • 2
  • 21
  • 35
Pablo
  • 1,627
  • 16
  • 16
42

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

Aminu Kano
  • 2,059
  • 1
  • 23
  • 24
  • 1
    if you're using webpack-devserver you won't see changes until you restart it. – Isaac Pak Apr 27 '19 at 21:21
  • This 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). – Jorge Mauricio Jul 22 '20 at 23:18
  • @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? – Linas M. Nov 01 '20 at 20:56
  • @LinasM. yeah sure, but what do you mean by "online"? – Aminu Kano Nov 02 '20 at 11:44
  • Well, 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 – Linas M. Nov 02 '20 at 12:18
  • @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. – Aminu Kano Nov 03 '20 at 07:38
  • 1
    @AminuKano, Yes, that explained the point very clearly. Thank you – Linas M. Nov 03 '20 at 15:43
29

1. Create the .env file on your root folder

some sources prefere to use .env.development and .env.production but that's not obligatory.

2. The name of your VARIABLE -must- begin with REACT_APP_YOURVARIABLENAME

it seems that if your environment variable does not start like that so you will have problems

3. Include your variable

to include your environment variable just put on your code process.env.REACT_APP_VARIABLE

You don't have to install any external dependency

Carlos
  • 1,368
  • 11
  • 9
26

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).

Sandeep Amarnath
  • 2,957
  • 1
  • 22
  • 31
14
  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL
Fatema Tuz Zuhora
  • 2,674
  • 1
  • 18
  • 33
  • How 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? – ameyaraje Jun 26 '20 at 16:16
  • @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! – Fatema Tuz Zuhora Jun 27 '20 at 17:53
  • process.env.REACT_APP_API_KEY is not giving value showing undefined. I did stop server and restarted with npm start – vikramvi Oct 06 '20 at 12:27
  • @vikramvi Do you put the value in a variable named same `REACT_APP_BASE_URL` in the .env file? – Fatema Tuz Zuhora Oct 07 '20 at 14:06
  • @FatemaT.Zuhora it was my bad, I had put .env in child directory by mistaken instead of putting it under root directory – vikramvi Oct 08 '20 at 01:50
  • @vikramvi Glad to know you've fixed it. – Fatema Tuz Zuhora Oct 08 '20 at 04:06
9

You have to install npm install env-cmd

Make .env in the root directory and update like this & REACT_APP_ is the compulsory prefix for the variable name.

REACT_APP_NODE_ENV="production"
REACT_APP_DB="http://localhost:5000"

Update package.json

  "scripts": {
    "start": "env-cmd react-scripts start",
    "build": "env-cmd react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
Ankit Kumar Rajpoot
  • 5,032
  • 1
  • 38
  • 28
5

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

anonym
  • 3,712
  • 9
  • 39
  • 66
5

I want to explain well how to solve this problem to prevent the undefined issues:

  • First, Adding Development Environment Variables In .env is available with react-scripts@0.5.0 and higher. This means u do not have to install anything .
  • Second create your .env file or .env_developement file or whatever and place ur variable but and this is the big but add REACT_APP_ to each variable name for ex REACT_APP_API_KEY= "secret_key_here". Without adding REACT_APP_ you will get undefined issue.
  • Now, You can simply use this variable process.env.REACT_APP_VARIBALE_NAME. for ex: const API_KEY = process.env.REACT_APP_API_KEY.
  • Finally, we solved this miserable situation .
DINA TAKLIT
  • 4,804
  • 9
  • 56
  • 64
1

The everyone got undefined the solution is put your .env file in root directiory such as

  • project-name/
  • src
  • .env

Dont Create in src Folder create in root directory of your app

It think u guys created file in src folder because i also created there only... Then only i realised it is wrong so create .env file in outer of src It will Works