300

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

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);
     });
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Biii
  • 3,041
  • 4
  • 9
  • 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
  • 9
    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
  • 7
    You can't hide secrets in a react app. See stackoverflow.com/a/46839021/4722345 – JBallin Nov 01 '18 at 19:55
  • 32
    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

12 Answers12

378

Four 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 (create-react-app) then you only need step 3 and 4, but keep in mind a variable needs to start with REACT_APP_ for it to work.

Reference: Adding Custom Environment Variables

Note - You need to restart the application after adding a variable in the .env file.

Reference: Using the dotenv package to create environment variables

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tarzen chugh
  • 10,561
  • 4
  • 20
  • 30
  • 82
    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
  • 15
    where do I add ```require('dotenv').config()```? which file? – aqteifan Feb 03 '20 at 20:38
  • 2
    @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
  • 4
    @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
  • 2
    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
  • %REACT_APP_WEBSITE_NAME% only works in build time. – SajithK Feb 05 '21 at 03:19
  • 1
    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
  • 3
    This accepted answer needs to be corrected. You simply cannot put secret keys in REACT_APP as it makes it accessible to the end user in plain text – Simen L Jan 28 '23 at 13:12
245

This solution does not require any extra packages.

Step 1 ReactDocs

In the above documentation they mention export in Shell and other options, and 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 the 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

After I did step 1.1|2, it was not working, but then I found the above issue/solution. React reads/creates env when it is built, so you need to run npm run start every time you modify the .env file, so the variables get updated.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
T04435
  • 12,507
  • 5
  • 54
  • 54
  • 27
    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
  • 11
    I have tried everything. `process.env.REACT_APP_API_KEY` says `undefined`. – Michale Rezene Oct 14 '20 at 20:42
  • For those who are getting `undefined` it is necessary to **restart the application**! This way react-script will save the value of the environment variable – Ícaro de Barros Oct 31 '22 at 19:56
131

There is a now 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 JavaScript file in the following way:

process.env.REACT_APP_API_KEY

React have supported environment variables since react-scripts@0.5.0. You don't need an external package to do that.

Adding Development Environment Variables In .env

*Note: I propose .env.local instead of .env because create-react-app adds this file to gitignore when creating 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 information: Adding Custom Environment Variables

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pablo
  • 2,137
  • 1
  • 17
  • 16
69

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
  • 5,463
  • 3
  • 33
  • 43
48

Webpack Users

If you are using Webpack, you can install and use the 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 the 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 dotenv-webpack.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aminu Kano
  • 2,595
  • 1
  • 24
  • 26
  • 1
    if you're using webpack-devserver you won't see changes until you restart it. – Isaac Pak Apr 27 '19 at 21:21
  • @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
35

1. Create the .env file on your root folder

Some sources prefer 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, you will have problems.

3. Include your variable

To include your environment variable, just put process.env.REACT_APP_VARIABLE in your code.

You don't have to install any external dependency

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carlos
  • 3,480
  • 1
  • 16
  • 14
15
  1. Install dotenv as devDependencies:

    npm i --save-dev dotenv
    
  2. Create a .env file in the root directory:

    my-react-app/
    |- node-modules/
    |- public/
    |- src/
    |- .env
    |- .gitignore
    |- package.json
    |- package.lock.json.
    |- README.md
    
  3. 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
    
  4. [ 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;
    
  5. Or you can simply just call the environment variable in your JS file in the following way:

    process.env.REACT_APP_BASE_URL
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fatema Tuz Zuhora
  • 3,088
  • 1
  • 21
  • 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
11

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 you do not have to install anything .
  • Second, create your .env file or .env_developement file or whatever and place your variable, but, and this is the big but, add REACT_APP_ to each variable name, for example, REACT_APP_API_KEY= "secret_key_here". Without adding REACT_APP_, you will get the undefined issue.
  • Now, you can simply use this variable: process.env.REACT_APP_VARIBALE_NAME. For example: const API_KEY = process.env.REACT_APP_API_KEY.
  • Finally, we solved this miserable situation .
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
10

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,188
  • 2
  • 38
  • 32
7

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anonym
  • 4,460
  • 12
  • 45
  • 75
6

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

  • project-name/
  • src
  • .env

Don’t create it in the src Folder. Create it in the root directory of your app.

It think you created the file in the src folder, because I also created it there only... Then only did I realise it was wrong, so I created the .env file in the outer of src. It will work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

You have to run npm start again once you set up the environmental variable. That was the missing part for me. The .env variables do not get updated on auto reloading.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131