Home > front end >  How to access env variables using react?
How to access env variables using react?

Time:03-25

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"

CodePudding user response:

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.

CodePudding user response:

you don't need explicit define that my variable is string or number etc .env do it himself first you can access it using

process.env.REACT_APP_SERVICE_ID

or a better way is to create a config.js file and inside you export all the .env variables like this

export default {
  SERVIVE_ID: process.env.REACT_APP_SERVICE_ID,
  TEMPLATE_ID: process.env.REACT_APP_TEMPLATE_ID,
  VAR: process.env.REACT_APP_VAR
};

after that import, it and you are good to go.

  • Related