reactjsenvironment-variables

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"

Solution

  • 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.