David whyte
David whyte

Reputation: 2061

react evironment variables .env return undefined

I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from '../src/components/Home'
import dotenv from  'dotenv'
import path from 'path'


class App extends Component {
  render() {
    console.log(process.env.API_URL)
    return (
      <div>
        <Home/>
      </div>
    );
  }
}

export default App;

Upvotes: 194

Views: 241900

Answers (25)

user1656204
user1656204

Reputation: 131

Had the same issue and spent a good amount of time searching for a solution to realize it was the naming of the file!

So, to make sure you're good to go:

1- Follow these rules for naming the .env file:

  • For the default environment, name the file: .env
  • For environment-specific files: .env.development OR .env.production OR .env.test
  • For custom environments: e.g -> .env.staging

2- Make sure you've placed the .env file in the root directory - same level as package.json file

3- Make sure your variables start with REACT_APP_ , for example: REACT_APP_VERSION OR REACT_APP_BASE_URL

  • As stated on their documents:

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.

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

4- After making any changes in .env file(s), make sure you stop and restart the server using npm start OR yarn start

Hope it helps someone!

Upvotes: 0

Max Lav
Max Lav

Reputation: 11

kiranvj answer is correct, only one thing to add, spent almost 30mins to notice it, you should remove the new line after the "=" sign, it could be added by VS Code automatically if you have string wrap switched on or if you accidentally used "Alt + Z".

WRONG

REACT_APP_API_URL=
 https://localhost

CORRECT

REACT_APP_API_URL=https://localhost

Upvotes: 0

abdelrahman aboneda
abdelrahman aboneda

Reputation: 790

For those who have same issue in react native-expo app make sure that your variable starts with EXPO_PUBLIC_

ex for .env'

EXPO_PUBLIC_VARIABLE=12324

Upvotes: 0

Satya Dewangan
Satya Dewangan

Reputation: 21

I also got the same error but in my case I wasn't getting the env variable which I recently added. This Error was fixed by stopping and restarting the react app.

Upvotes: 0

JISHNU T RAJ
JISHNU T RAJ

Reputation: 18

When you have two .env folders with same name, it will not work. For both frontend and backend, either you should use .env.development or .env.local in the frontend and .env for the backend. This setup works for me.

Upvotes: 0

Mohd. Anas Siddiqui
Mohd. Anas Siddiqui

Reputation: 783

When I was trying to access the .env variable it was throwing error: "process is not defined"

I have read all the StackOverflow articles and the official documentation as well but still haven't found the solution.

So, my solution is: mistakenly process is defined as a variable in my code. That is why was getting errors. You have to change the process variable name to another name. And it will work fine.

Hope it helps you. Thanks.

Upvotes: 0

kiranvj
kiranvj

Reputation: 34147

Three things to note here

  1. the variable must be prefixed with REACT_APP_

    eg: REACT_APP_WEBSITE_NAME=hello

  2. You need to restart the server to reflect the changes.

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

After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE

Additional tips

  1. No need to wrap your variable value in single or double quotes.
  2. Do not put semicolon ; or comma , at the end of each line.

Read more here(my own post) and the official docs

Upvotes: 548

Anton L.
Anton L.

Reputation: 828

I just found that I used different names for the variables :)

Upvotes: 0

Anilkumar Kalyane
Anilkumar Kalyane

Reputation: 119

I investigated a couple of options on how to set environment-specific variables and ended up with this:

You can directly use the dotenv-webpack(npm install dotenv-webpack --save) available in webpack to have access to any environment variable.

You just have to declare the plugin in your webpack.config.js file:

const path = require('path')
const Dotenv = require('dotenv-webpack')

module.exports = {
  /*...*/
  plugins: [
    new Dotenv()
  ]
}

Just create the .env file in your root directory and set the variables there,

REACT_APP_API_URL=https://localhost:8080/api
REACT_APP_LOG_PATH=/usr/share/

Then you call it in your js file in the following way:

process.env.REACT_APP_API_URL
process.env.REACT_APP_LOG_PATH

Upvotes: 0

Mara
Mara

Reputation: 403

Also make sure that when you enter process.env.REACT_APP_YOURVARIABLE, your IDE don't add at the top of your file:

import process from "process";

This was my problem, I received undefined until I removed the accidentally added import

Upvotes: -2

Johann
Johann

Reputation: 12408

In my case I started with naming the file process.env. As it happen and as the doc clearly states, the file should simply be named .env

Upvotes: 3

Mariusz Sidorowicz
Mariusz Sidorowicz

Reputation: 366

If you are using dev server on localhost know this that .env doesn't work here, you need to deploy website on "normal" server, it is a safety reason to not allow browser to see .env in staging

Upvotes: 0

Safi Habhab
Safi Habhab

Reputation: 1077

when calling a .env variable from a JS file you need to call it by process.env. prefix before you write the .env variable

thus it would look like process.env.REACT_APP_NOT_SECRET_CODE

and do not forget to start your variable name by REACT_APP_ prefix as mentioned in previous answers, otherwise react will ignore it for security reasons.

Upvotes: 28

Safaetul Ahasan Piyas
Safaetul Ahasan Piyas

Reputation: 1783

Solution:
1.Remove double quotation.("...").
2.Prefix Must be REACT_APP on every variable.

Right way:

REACT_APP_API_URL=http://localhost:8002

I hope its work.

Upvotes: 3

Tushar Walzade
Tushar Walzade

Reputation: 3819

No need to prefix it with REACT_APP_, just identify your environment -

  • if you are on development environment (npm start), you should be adding an environment variable in .env.development like - API_URL=http://example.com
  • if you are on production environment, updating .env should work

Then use the same in your JS file as process.env.API_URL

Note: I've tested this on React JS v16.8

Upvotes: 0

DO NOT STORE OR USE API KEYS IN FRONTEND CODE SINCE IT IS EASILY READABLE THROUGH DEV TOOLS

Saving API keys in .env and using them in your React app will still be unsecured since the API key can be read from DevTools.

Use some simple backend code that will act as a proxy to your service.

Send required data through a request and then the backend should use that data including the API key stored on the backend, and then make a request to some particular service that needs that API key.

Upvotes: 0

FIX:

in babel.config.js, if you're using the optional configuration:

    {
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "blacklist": null,
      "whitelist": null,
      "safe": false,
      "allowUndefined": true
    }]
  ]
}

you should then import:

import {API_URL, API_TOKEN} from "@env"

instead of:

import {API_URL, API_TOKEN} from "react-native-dotenv"

the NPM Package description itself has this inconsistency

Upvotes: 0

Magda
Magda

Reputation: 221

  1. restart the vscode (close the project, close the editor)
  2. open it again
  3. launch the project

In my case it help a lot. Also remember to start the name of your key with REACT_APP_YOUR_NAME_KEY

Upvotes: 8

suranga upul
suranga upul

Reputation: 259

try by clearing the cache also.

npx react-native start --reset-cache

Upvotes: 1

Alok Mishra
Alok Mishra

Reputation: 107

If the above solutions don't work for you then please check where is your ".env" file place. Like in my case everything I had done correctly but the mistake is I had placed the ".env" outside my project directory due to which I'm getting error.

Note: Your ".env" file should be in the same directory in which your "package.json" is.

Upvotes: 4

Thanapooom Ptjrk
Thanapooom Ptjrk

Reputation: 371

  • Add prefix REACT_APP_ on React environment variables.

    apiKey: process.env.REACT_APP_API_KEY
    
  • Make sure .env file is in the root directory.

    src/
    .env
    .gitignore
    package.json
    package-lock.json
    
  • Restart the development server after making changes in .env file.

  • Copy only the value inside the quotation marks and don't forget to remove trailing commas(It haunted me for several hours). These examples will give you an error.

    REACT_APP_API_KEY=Ach2o1invVocSn25FcQhash209,
    REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209",
    REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209"
    

Upvotes: 23

akshay Tiwari
akshay Tiwari

Reputation: 135

  • Make sure you used the prefix REACT_APP on every variable

  • Confirm that the variable names on the .env file match the ones on
    your js file.For example,REACT_APP_KEY in .env versus process.env.REACT_APP_KY

  • If the development server was running, stop it then rerun using npm start it. I really struggled with this (variable is an undefined error).
  • Every time you update the .env file, you need to stop the server and rerun it, as the environment variables are only updated during build (variable is an undefined error).
  • Remove quotations from the values of the variables.
// Wrong: 
REACT_APP_KEY=”AHEHEHR”

// Right:
REACT_APP_KEY=AHEHEHR

Upvotes: 11

CyberMessiah
CyberMessiah

Reputation: 1270

Another possible trap in which I fell was to define the variables not under the create-react-app folder but one above(where the Node server/backend .env is located). Make sure you don't do that because you will waste precious time, as I did today.

Upvotes: 2

David whyte
David whyte

Reputation: 2061

Hey thanks guy what i did and worked was create a config.js file

 const dev={
    API_URL:"http://localhost:300"
}

const prod={
    API_URL:"llll"
}
const config=process.env.NODE_ENV=='development'?dev:prod
export default  config

Then i import wherever maybe in a component and get my data.

Upvotes: 2

tingxuanz
tingxuanz

Reputation: 426

You will probably need to call dotenv.config() as suggested by the document

If you are using create-react-app, you don't need dotenv package. You will need to add REACT_APP_ prefix to the variable name in .env file. See the document here

Upvotes: 34

Related Questions