0

I am trying to access a variable in my .env file. Unfortunately, I am getting an undefined back.

.env file

REACT_APP_SOCKET_URL = ws://localhost:2900

attempt to access it

useEffect(() => {
 console.log(process.env.REACT_APP_SOCKET_URL); //undefined
},[]);
Captai-N
  • 1,124
  • 3
  • 15
  • 26
  • Please check duplicate question here: https://stackoverflow.com/questions/53237293/react-evironment-variables-env-return-undefined – sedhal Sep 08 '22 at 09:36
  • Does this answer your question? [react evironment variables .env return undefined](https://stackoverflow.com/questions/53237293/react-evironment-variables-env-return-undefined) – Sumit Singh Sep 08 '22 at 09:37
  • no duplicate. I use the prefix REACT_APP – Captai-N Sep 08 '22 at 09:39
  • @SumitSingh That's the same question linked above by sedhal. – AKX Sep 08 '22 at 09:39
  • I created the app using create-react-app. that's why I don't need dotenv – Captai-N Sep 08 '22 at 09:40
  • Having environment variables available in `process.env` at runtime is a feature of `create-react-app`. As in, there needs to be build-time script that copies the env vars from the nodejs shell env into the frontend build. This also means there needs to be a script that uses the dotenv nodejs dependency. – timotgl Sep 08 '22 at 09:40

1 Answers1

1
  1. Make sure you're using an up-to-date version of create-react-app, using .env hasn't always been supported https://create-react-app.dev/docs/adding-custom-environment-variables
  2. Make sure .env is located in the project root where package.json is.
  3. Try not having spaces in .env, try putting the value in double quotes ("ws://localhost:2900")
  4. Restart the dev server, changes to .env aren't picked up automatically as it works for hot module reloading
timotgl
  • 2,865
  • 1
  • 9
  • 19