Search code examples
javascriptreactjsenvironment-variablesdotenv

.env file not updating in local environment in react js


I do have a .env file in my react project and using dotenv package to read the environment variables. I did a console log of the environment variables. I had initialized few variables in the beginning in .env file and was being read perfectly.

Later I changed some data in the .env file and restarted the local server, but new changes were not being reflected. EVEN after deleting the .env file and starting the server, the same old variables are loaded. I know it's a cache issue but could not figure out a way to reset it.

I am using npm start command to start the server.


Solution

  • Use REACT_APP prefix

    You need to declare variables with REACT_APP prefix as per the documentation.

    REACT_APP_API_KEY = 'XXXXXXXX'
    REACT_APP_AUTH_DOMAIN = 'XXXXXXXX'
    REACT_APP_DATABASE_URL = 'XXXXXXXX'
    REACT_APP_PROJECT_ID = 'XXXXXXXX'
    REACT_APP_STORAGE_BUCKET = 'XXXXXXXX'
    REACT_APP_MESSAGING_SENDER_ID = 'XXXXXXXX'
    REACT_APP_API_ID = 'XXXXXXXX'
    REACT_APP_MEASUREMENT_ID = 'XXXXXXXX'
    

    And similarly, access them with the prefix in your code

    console.log(process.env.REACT_APP_PROJECT_ID);
    

    Note: You need to restart the dev server every time you update the env file to consume the changes.