0

when i tried to get the value from .env file, it says undefined, i have defined variable in .env API_URL, is there anything which i am missing in react js ? i am using dotenv npm, can anyone please help me how to resolve this issue ? here i have uploaded my code, any help will be really appreciated

const dotenv = require('dotenv');
const fs = require('fs');
alert(process.env.API_URL);

.env

API_URL=https://********/api/v1/
1
  • If its create react app with no webpack ejected, then env variables have to be prefixed with REACT_APP, so you should have REACT_APP_API_URL env variable and you do not need dotenv to get those variables. More info Create react app docs Commented Sep 24, 2020 at 13:41

2 Answers 2

4

The two important things to remember when defining Environment Variables in your react project

  1. Always reload your application after making a change to the .env file
  2. Always prefix your variables with REACT_APP_
Sign up to request clarification or add additional context in comments.

Comments

1

Check whether the .env file is in the root folder of working directory

As per the react documentation : 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. Changing any environment variables will require you to restart the development server if it is running.

3 Comments

it is in root folder
It is not React documentation but CRA documentation. React does not require REACT_APP prefix, it is CRA that requires the prefix. Your solution may work (if the app is CRA) but it is misleading, so please fix the issue in your answer.
I thought you started using create react app as Nikul Panchal said is what exactly i was trying to say!

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.