Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access env variables using react?

This might be a repeat, but I can't find an answer for my particular use case. I have a react app created using npx create-react-app app and a .env file in my root directory. Appending "REACT_APP" to my variables don't register under process.env, with the only variables being registered are FAST_REFRESH: true, NODE_ENV: "development", PUBLIC_URL: "", WDS_SOCKET_HOST: undefined, WDS_SOCKET_PATH: undefined, and WDS_SOCKET_PORT: undefined. How do I access the environment variables in my .env file?

Here are my vars:

REACT_APP_SERVICE_ID="service"
REACT_APP_TEMPLATE_ID="template"
REACT_APP_VAR="show"
like image 236
Darien Miller Avatar asked Mar 02 '26 18:03

Darien Miller


2 Answers

I had the same problem: Only the predefined env variables were printed, my custom variables – although prefixed with REACT_APP were printed as undefined in dev mode when I tried to get them with process.env.REACT_APP_MYVAR.

Stopping the local host and starting the app once again with 'npm start' fixed the issue.

like image 99
mirja-t Avatar answered Mar 05 '26 11:03

mirja-t


Here are the docs for adding custom environment variables: https://create-react-app.dev/docs/adding-custom-environment-variables/.

It should be as simple as process.env.REACT_APP_SERVICE_ID.

like image 27
proph3t Avatar answered Mar 05 '26 12:03

proph3t