Search code examples
javascriptnode.jsvite

Unable to load environment variable in vite.config.js


I am working on a Vite project where I need to load an environment variable (APP_PORT) from a .env file in my vite.config.js. However, it seems that the variable is not being loaded correctly, and my fallback value (5000) is being used instead.
Project structure:.

project/
├── .env
├── frontend/
│   ├── vite.config.js
│   └── ...

The .env file is located in the root directory of the project. The vite.config.js file is inside the frontend folder.
.env file

APP_PORT=5001

vite.config.js file

import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default ({ mode }) => {
  // Load environment variables for the current mode
  const env = loadEnv(mode, path.resolve(__dirname, '../', ''));
  const port = env.APP_PORT;
  console.log(
    'Loaded environment variables for mode:', env,
    'Path:', __dirname,
    'Port:', port);

  return defineConfig({
    root: 'frontend',
    plugins: [react()],
    optimizeDeps: {
      exclude: ['lucide-react'],
    },
    server: {
      proxy: {
        '/api': {
          target: `http://127.0.0.1:${port || '5000'}`, // Use the loaded env variable
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, ''),
          configure: (proxy) => {
            proxy.on('proxyReq', (proxyReq, req) => {
              console.log('Proxying request:', req.url, 'to:', proxyReq.getHeader('host'));
            });
          }
        }
      }
    }
  })
};

Even though I’ve specified APP_PORT in the .env file, it always falls back to the default value (5000). The console.log in vite.config.js shows undefined for APP_PORT.
What I have tried:
1. Verified the .env file is in the root directory and contains the correct variable (APP_PORT=5001).
2. Restarted the Vite development server after making changes to the .env file.
3. Ensured that path.resolve(__dirname, '../') points to the correct directory for the .env file.
4. Added a debug log to check the loaded environment variables, but I get undefined.
Expected Behavior: The APP_PORT variable from the .env file should be loaded, and the proxy in vite.config.js should use port 5001.
Environment:. Node: v23.4.0 VITE: v6.0.3 OS: macOS


Solution

  • The issue is likely because your vite.config.js file is located in the frontend subdirectory, while your .env file is in the root of your project. By default, Vite looks for .env files relative to the location of the vite.config.js file or the root directory set in the Vite configuration.

    To resolve this issue, you have a few options:

    Option 1: Set the root in vite.config.js You can tell Vite to treat the root directory of your project as the base. Update your vite.config.js like this:

    import { defineConfig } from 'vite';
    export default defineConfig({
        root: '../', 
        server: {
            port: process.env.APP_PORT || 5000, or fallback
        },
    });

    Option 2: Use dotenv library

    import { defineConfig } from 'vite';
    import dotenv from 'dotenv';
    import path from 'path';
    
    dotenv.config({ path: path.resolve(__dirname, '../.env') });
    
    export default defineConfig({
        server: {
            port: process.env.APP_PORT || 5000, e or fallback
        },
    });

    Option 3: Move Vite Config to Root folder