Loading process env variables into your vite project (for DEV only)

Need environment variables only during development (like debug flags or local API URLs)? Here’s how to conditionally load them in Vite without leaking secrets:

June 11, 2025
// ⚠️ be careful what envs you load into vite for production builds because any env consumed by the built code will be sent to the client
// vite.config.ts
export default defineConfig(({ mode }) => {
  const devEnv = mode === "development" 
    ? loadEnv("development", process.cwd(), ["VITE_", "DEV_"]) 
    : {};

  return {
    server: {
      port: Number(devEnv.VITE_PORT || 3000),
    },
    define: {
      __DEV__: mode === "development", // Expose dev mode globally
    },
  };
});