Home  >  Q&A  >  body text

How to use a single .env file for a full stack React + Node application?

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?

P粉983021177P粉983021177378 days ago694

reply all(1)I'll reply

  • P粉203648742

    P粉2036487422023-09-09 14:36:36

    I found a messy solution, maybe someone can suggest some cleaner solution.

    1. To set the port dynamically in the vite.config file, I wrote the following code:
    import { defineConfig, loadEnv } from "vite";
    import react from "@vitejs/plugin-react";
    import path from "path";
    
    export default ({ mode }) => {
      process.env = { ...process.env, ...loadEnv(mode, path.resolve(__dirname, "../")) };
      return defineConfig({
        plugins: [react()],
        envDir: "../",
        server: {
          port: process.env.VITE_CLIENT_PORT,
        }
      })
    }
    1. 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.

    2. Now, in my React project, I can use environment variables like this: import.meta.env.VITE_SERVER_PORT

    3. To use env variables in my Node project, I can use dotenv like this (while also configuring the .env path):

    const express = require('express');
    require('dotenv').config({ path: '../.env' });
    const app = express();
    
    app.listen(process.env.VITE_SERVER_PORT, () => {
        console.log(`Server running on port ${process.env.VITE_SERVER_PORT}`);
    })

    reply
    0
  • Cancelreply