[reactjs] Adding an .env file to React Project

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.

_x000D_
_x000D_
performSearch = (query = 'germany') => {_x000D_
    fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${REACT_APP_API_KEY}`)_x000D_
    .then(response => response.json())_x000D_
    .then(responseData => {_x000D_
        this.setState({_x000D_
            results: responseData.results,_x000D_
            loading: false_x000D_
        });_x000D_
     })_x000D_
     .catch(error => {_x000D_
            console.log('Error fetching and parsing data', error);_x000D_
     });_x000D_
}
_x000D_
_x000D_
_x000D_

This question is related to reactjs environment-variables api-key

The answer is


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"
  }

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 en your js file in that way:

process.env.REACT_APP_API_KEY

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


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


  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

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


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.


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


Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

Examples related to api-key

Adding an .env file to React Project Googlemaps API Key for Localhost Best practice for storing and protecting private API keys in applications Place API key in Headers or URL What is an API key?