Darien Miller
Darien Miller

Reputation: 753

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"

Upvotes: 2

Views: 27351

Answers (4)

RaFi
RaFi

Reputation: 1

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

that will works

Upvotes: 0

mirja-t
mirja-t

Reputation: 143

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.

Upvotes: 6

Abbas Hussain
Abbas Hussain

Reputation: 1395

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.

Upvotes: 3

proph3t
proph3t

Reputation: 965

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.

Upvotes: 4

Related Questions