How to access environment variable in react?

I added react into django using webpack and when I created .env file in app_name/, I am trying to access environment variable like this process.env.base_url but I am getting undefined.

file structure

Django_React

  -- app_name
       -- src
       -- .env
       -- urls.py
       ...
       ...
  ...
  ...

How can I create and access environment variable if react app is created like this ?

Such issue could lead from naming convention.

According to React Doc - Adding Custom Environment Variables

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.

So, maybe you could try to

  1. add REACT_APP_ at the beginning of your environment variable name, like process.env.REACT_APP_base_url;
  2. restart the development server;
  3. access environment variable by process.env.REACT_APP_base_url.

Hope this helps.

Back to Top