React app unable to access root's env file

Viewed 792

Context: - MERN stack app - Deployed to Heroku - React app created with create-react-app

Here is my folder structure:

folder structure

In my server app.js, I can access the .env variables by requiring it like this: require('dotenv').config({ path: '../.env' });

I am trying to access the env variables on my React app, but I cannot seem to access the variables in the root .env file, and I cannot seem to specify the path in React (can I?) for the .env like in server/app.js.

The only way I can get it to read any .env variable value is if I move the .env file to the client directory, so my workaround for now is to move .env to my client directory and update the code in my server to require it as such: require('dotenv').config({ path: '../client/.env' });

This workaround fixes it, but is there a better way/best practice to allow for the .env file be in the root folder?

Do I need to eject create-react-app and set up some custom configurations?

More info:

My local .env file contains:

REACT_APP_API_URL=http://localhost:5000

My client/package.json scripts:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
1 Answers
Related