342

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);
     });
}

6
  • 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 :/ Commented Mar 30, 2018 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. Commented Oct 26, 2018 at 4:12
  • 7
    You can't hide secrets in a react app. See stackoverflow.com/a/46839021/4722345 Commented Nov 1, 2018 at 19:55
  • 34
    DO 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. Commented Jun 19, 2019 at 23:36
  • 3
    You need to setup a server and use authentication like JWT in order to hide it. Read this suggestion for more info. Commented Jun 12, 2020 at 8:13

12 Answers 12

414

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

Sign up to request clarification or add additional context in comments.

14 Comments

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".
where do I add require('dotenv').config()? which file?
@aqteifan u don't need to add that snippet, but then .ENV files naming plays a vital role
@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.
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
|
274

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.

8 Comments

@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 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?
@KannanT You will need .env.[ENVIRONMENT]
@T04435 I already have mate what I was referring is do I need I have different.env files for each server?
I have tried everything. process.env.REACT_APP_API_KEY says undefined.
|
141

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

process.env.REACT_APP_API_KEY

React has supported environment variables since [email protected]. 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

5 Comments

Proper naming did the job for me. I used .env.dev and React fell back to .env as it was looking for .env.development
and one tip is restart server to work well
also do not use any quotes or spaces in the variable definition REACT_APP_GOOGLE_MAP_API_KEY=qweqwew88754
The "proper naming", as mentioned by @Omnibyte, can be referenced here: create-react-app.dev/docs/adding-custom-environment-variables/…
Really old post, but that Files priority saved my day.
88

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

7 Comments

I think restarting the project app is necessary after following this process.
Should it be possible to generate .env file when running docker-compose up?
So you say no dotenv-cli installation is needed? And I don't have to manually inject the .env variables like "start": "dotenv -e .env next start",
@CsabaToth no you don't need dotenv-cli installation. Create react app works out of the box with this. If you're using vite then please check this out vite.dev/guide/env-and-mode
Thanks, storing the .env file in the root folder is an important step.
|
55

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.

5 Comments

if you're using webpack-devserver you won't see changes until you restart it.
@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?
@LinasM. yeah sure, but what do you mean by "online"?
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
@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.
39

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

6 Comments

I do the same thing but it shows undefined in console
If you are getting the values as undefined, recompile again.
after recompile still getting undefined. console.log('process', process.env.REACT_APP_BASE_URL);
Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
This is key: The name of your VARIABLE -must- begin with REACT_APP_YOURVARIABLENAME
|
19
  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
    

2 Comments

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 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!
12

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 [email protected] 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 😇.

1 Comment

Do I need to install dotenv CLI?
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"
  }

2 Comments

Doing this results in a terminal error: 'env-cmd' is not recognized as an internal or external command,.
You have to install the env-cmd package first, you can install locally by giving this command to your project directory npm install env-cmd or to install globallyt npm install -g env-cmd.
9

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

1 Comment

Thank you. I was wondering as to why it was not working.
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.

3 Comments

What do you mean by "The everyone got undefined"? It is incomprehensible.
@PeterMortensen why do you make unnecessary edits for all our answers here? I see that all the answers have your name as an editor (including mine but I just declined your edit as it was unnecessary)
@Deepak Aravind, you could go and do a Rollback if you don't like the edit
3

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.

1 Comment

CRA is deprecated in 2025, If you're using Vite instead and cannot access the values from .env, try the following steps, 1. In the .env file: save the variable names with the "VITE_" prefix, like: VITE_API_key=456789 2. In React File: use import.meta.env.VITE_{key} to get the value from the .env file, like: const apiKey = import.meta.env.VITE_API_URL; //456789

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.