2

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"
3

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

Comments

0

you can create .env file in root folder and then to get access .env variables write :"import.meta.env..API_KEY"

that will works

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.