296

I am using create react app to bootstrap my app.

I have added two .env files .env.development and .env.production in the root.

My .env.development includes:

API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback

When I run my app using react-scripts start and console out process.env it spits out

{ NODE_ENV: "development", PUBLIC_URL: "" }

I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!

Directry structure is:

/.env.development
/src/index.js

Package.json script is:

"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
    "client:start": "export PORT=3005; react-scripts start",
    "server:start": "node server.js",
    "build": "react-scripts build",

Edit:

@jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.

Edit 2

It works okay if I name the file .env but not if I use .env.development or .end.production

6
  • Can you post your package.json file ? Commented Jan 22, 2018 at 9:33
  • 3
    process.env is something that the back-end (Node or whatever you're using) can read. The front-end bundle has no idea what process.env is as it runs in the browser. You can configure webpack to pass it in the bundle when bundling, or even easier you can pass it from the back-end in the index file you're rendering as a global variable. Commented Jan 22, 2018 at 9:35
  • probably not the case, but i have run into this a couple of times and the problem i found is that when my computer is using a lot of memory i don't get my .env variable loaded. I use ubuntu 16.4. try loading the varible from the terminal react-scripts start API_URL=http://localhost:3000/api CALLBACK_URL=http://localhost:3005/callback if you still don't see them i'd restart my system to lower memory usage and try again usually this resolves it for me. Commented Jan 22, 2018 at 9:39
  • 1
    @RaulRene create-react-app handles .env out of the box for you not need for further config Commented Jan 22, 2018 at 9:41
  • 1
    .env is the file name, not the ending! Don't make the mistake of calling your file secret.env or similar, that won't work! Commented Feb 4, 2023 at 18:05

35 Answers 35

650
+350

With create react app, you need to prefix REACT_APP_ to the variable name. ex:

REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback

** Make sure your .env file is in the root directory, not inside src folder.

CRA Docs on Adding Custom Environment Variables:

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name

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

12 Comments

This is vital. i missed it but yeah it won't work with the prefix
This works when I use .env but not for .env.development or .env.production ?
@shenku Did you manage to find out why it works only with .env and not with .env.development and env.production
I stopped my development server and started it again and saw that my Env variables are picked up. I have 2 files .env and .env.local in my root folder.
Vital bit of information after the change, restart the server as I had the same issue!
|
174

Make sure your .env file is in the root directory, not inside src folder.

2 Comments

Although, while reading the documentation I saw it should be in the root directory, I still managed to add my .env file in the src folder...(facepalm) Thanks for your answer.
I had the same problem, it didn't work when inside src folder but it worked after moving into root folder in version 3.4.3
77

Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.

Source: Github

Comments

33

If you want to use multiple environment like .env.development .env.production

use dotenv-cli package

add .env.development and .env.production in project root folder

and your package.json

"scripts": {
    "start": "react-app-rewired start",
    "build-dev": "dotenv -e .env.development react-app-rewired build",
    "build-prod": "dotenv -e .env.production react-app-rewired build",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"   
},

then build according to environment like

npm run-script build-dev 

7 Comments

is this dotenv or dotenv-cli?
Having different .env files for different environments is now also supported out of the box by create-react-app: create-react-app docs. No need to use dotenv explicitly (create-react-app actually uses it behind the scenes to handle environment variables)
@MariaJeysinghAnbu, that syntax belongs to dotenv-cli, not dotenv: npmjs.com/package/dotenv-cli
@AMS777 I'm using dotenv npm not dotenv-cli
@MariaJeysinghAnbu, I wanted to use dotenv but got an error. I checked the documentation but didn't find that -e option for the command line. However I found it on the dotenv-cli documentation. That's why I was saying. I'm finally using env-cmd, not to have dotenv and dotenv-cli installed at the same time, which may lead to confusion.
|
25

I was having the same problem, but it was because I had my .env file in YAML format instead of JS.

It was

REACT_APP_API_PATH: 'https://my.api.path'

but it needed to be

REACT_APP_API_PATH = 'https://my.api.path'

4 Comments

Such a simple yet good spot. I had done the same and couldn't see the wood for the trees. Thanks
Thanks for this! I was searching all day not noticing this slight error :)
Thank you for posting this. It's an easy mistake to make.
Ahhh I'm embarassed. +1
21

For people who apply all those answers above and didn't work just restart the terminal of npm start, stop the live server and run it again and it will work because it works for me

1 Comment

Stopping the live server and restarting is a critical step. This needs to be included in the top voted answer!
16

Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:

"scripts": {
    "build:local": "env-cmd -f ./.env.production.local npm run build",
    "build:production": "env-cmd -f ./.env.production npm run build"
  }

In your package.json file.

4 Comments

Thank you so much, this comment saved me. The create-react-app documentation hasn't updated this, so I was figuring out what is wrong
You totally saved me here. I was spinning on this thing. Thank you
somebody give this guy a medal
Thanks for this even in blogs they didn't give this commands properly
15

1- Make sure .env file is based your react app root directory

2- for react app you need to prefix REACT_APP_ to the variable name. ex: REACT_APP_API_URL

3- kill server and npm start again after .env file modify

2 Comments

Just for anyone coming to this the prefix REACT_APP_ is very important else it wont work
kill server and npm start again after .env file modify this worked for me. Thanks!
9

For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:

  "scripts": {
    "start": "env-cmd .env.development react-scripts start",
    "build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
  }

In your project root you have to create two files with the same env variables but with different values:

.env.development
.env.production

Then exclude them from public. For this in your .gitignore file add two lines:

.env.development
.env.production

So this is a proper way to use different env variables for dev and prod.

2 Comments

try to use full path, like: ./node_modules/.bin/env-cmd
but I do not recommend the approach in my answer. Now I know that react gives build in mechanic to work with .env
8

While working with .env file, be it frontend or backend.

  • Whenever you modify the .env file, you must restart the respective server for the changes to take effect in the application.
  • Hot reloading doesn't read changes from .env file.

Comments

6

Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables

that doc creates confusion.

So you actually need to put prefix REACT_APP_ within the .env to make it work.

And make sure that you restart the test/dev/prod server because the .env content change was loaded on the build stage.

Comments

5

If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.

Comments

5

when you get undefined from the environment file then just stop the terminal and restarts with npm start command.

Comments

4

And remember not to have semi-colon after the API key in the env-file.

REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';

should be

REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'

that was my error

Comments

4

There are different types of react app like vite react-app and normal react app.

Do the following steps first:

A. npm install dotenv --save

B. Add following line into your js file where you require environmental variables: require('dotenv').config()

C. In both kind of react app the .env file should be outside the source folder and should be right next to .gitignore and package.json file.

Second,

  1. If you are using vite react app, then write your environmental variables as follows where VITE_ is compulsory VITE_API_KEY=28y4nkrasdhew

    Now to access this, use the following syntax in your javascript file as import.meta.env.VITE_API_KEY

  2. Or if you are using normal react app, then write your environmental variables as follows where REACT_APP_ is compulsory REACT_APP_API_KEY=28y4nkrasdhew

    Now to access this, use the following syntax in your javascript file as process.env.VITE_API_KEY

Comments

3

I made the silly mistake of naming my file secret.env because that's how I always did it in Node.js. After changing the name to .env, restarting the terminal, and running npm start again, everything worked like a charm

1 Comment

I dont know how i missed this. Asking the wrong questions i guess. Thank you!
2

For any VS Code users, be aware that the .env.local env file is auto-sourced, but also auto-ignored from search results when you do a project wide search for MY_ENV_VAR(probably due to it being git ignored by default). This means that if you have MY_ENV_VAR= in your .env.local like me and forgot about it, it'll break things and you'll spend 15 mins being very confused.

Comments

2

Was struggling for a good hour before I noticed my kind IDE added an import:

import * as process from "process";

just remove it and you're fine, if that's your case as well.

Comments

2

After you add .env file, you need to

  • restart your application
  • kill the server
  • run npm start again

And it should work

Comments

2

The environment variable starts with REACT_APP_ (this is a must when using Create React App).

Comments

1

I had same issue that I wasn't able to access .env variable in App.js. and I had solved the problem use create correct .env file.

in my case I was copy file from different OS and use in ubuntu system so just I did "sudo touch .env" and added my variables and restart app again then it's working for me.

Comments

0

I didn't get any value back as well. For some reason, I thought the environment file should be dev.env, qa.env etc. Actually, it's just ".env". That's that. In case some else makes this mistake.

Comments

0

create-react does not supports hot reload feature .env files since they are not Javascript. So, when you change the env files make sure to manually start your server to see the effect of new changes.

In my case, a manual restart of the server worked fine :)

Comments

0

What worked for me was to install env-cmd and after that in my package.JSON add the following line of code

"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"

}

Comments

0

I forget to add process.env.

It looks like this

const domain = process.env.REACT_APP_AUTH0_DOMAIN;

Comments

0

first step:

in your .env.local file add REACT_APP_your_API_key in this way

second step:

Add your config file ${process.env.REACT_APP_Your_API_key}

the third step:

must restart your React App and then Test whether it works.

mainly, I forget the last step

1 Comment

Do you mean ${process.env.REACT_APP_Your_API_key} (. instead of _ after process.env)?
0

If none of the solutions above worked for you, give these potential solutions a shot:

  1. Make sure all the import statements within the file that is requiring defined environmental variables are being imported from the local project and not some other project(VSCode wrongly autocompleted some of my import statements in this manner)

  2. Try exiting your current Terminal instance and running the app in a new instance

Comments

0

Follow these 3 steps:

  1. Install dotenv

    npm install dotenv --save

  2. Add following line in your code:

    require('dotenv').config()

  3. Create a .env file in the root directory

Comments

0

In my case, simply restarting the application wasn't enough to access the environment variables. What worked for me was:

  1. Stopping the application (using Ctrl+C in the terminal)
  2. Rebuilding it with npm run build
  3. Starting it again with npm start

After this env vars were successfully loaded.

Comments

0

In addition to making sure you have an .env file in your root folder, be sure any REACT_APP_* config values come first in the .env file. If you have anything otherwise, react-scripts won't pick it up. (The other ENV values are used elsewhere in the code)

Doesn't work

SUPABASE_URL="https://identifier.supabase.co"
SUPABASE_ANON_KEY="12345"
REACT_APP_MAPBOX_TOKEN="XYZ"

Works

REACT_APP_MAPBOX_TOKEN="XYZ"
SUPABASE_URL="https://identifier.supabase.co"
SUPABASE_ANON_KEY="12345"

Sample code

import logo from './logo.svg';
import './App.css';
import React, { useRef, useEffect, useState } from 'react';
import mapboxgl from '!mapbox-gl'; // eslint-disable-line import/no-webpack-loader-syntax

mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN;

function App() {
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [lng, setLng] = useState(-70.9);
  const [lat, setLat] = useState(42.35);
  const [zoom, setZoom] = useState(9);

  useEffect(() => {
    if (map.current) return; // initialize map only once
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v12',
      center: [lng, lat],
      zoom: zoom
    });    
  }, []);

  return (
    <div className="App">
      <div>
        <div ref={mapContainer} className="map-container" />
      </div>
    </div>
  );
}

export default App;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.