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 exceptNODE_ENVwill be ignored to avoid accidentally exposing a private key on the machine that could have the same name.
So, maybe you could try to
- add
REACT_APP_at the beginning of your environment variable name, likeprocess.env.REACT_APP_base_url; - restart the development server;
- access environment variable by
process.env.REACT_APP_base_url.
Hope this helps.