I'm building my first full stack application using React and Node. The project has a root directory with a client folder (for the React subproject) and a server folder (for the Node subproject). I recently migrated my React project from create-react-app to Vite.
I want both frontend and backend to be able to read the server port, client port, and base URL (which is localhost for now) from a single .env file in the entire project root to avoid hardcoding values for these.
Having two separate .env files for client and server seems simple, since Vite can read from the .env file in the client directory, and Node can read from the .env file in the server directory. < /p>
How to enable the project to use a .env file in the root directory? Is it a good/standard practice to use one .env file instead of two?
I found a messy solution, maybe someone can suggest some cleaner solution.
I also added the
envDir
attribute to the file (shown above) to configure Vite/React to read environment variables from the root directory instead of the client directory.Now, in my React project, I can use environment variables like this:
import.meta.env.VITE_SERVER_PORT
To use env variables in my Node project, I can use dotenv like this (while also configuring the .env path):