Problem with loading environment variables in Vite + React + TypeScript
Hi! I’m working on a project with React, Vite, and TypeScript, but I can’t get the environment variables to load correctly. Even though I have the .env file in the same directory as the vite.config.ts file and I created a vite-env.d.ts file to declare the environment variables, they aren’t loading. Here’s the relevant information about my setup:
.env file:
env
VITE_API_URL=http://localhost:8081
VITE_IP_SERVER_GOCHAT=localhost
VITE_PORT_SERVER_GOCHAT=808
vite.config.ts file:
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
// Load environment variables for the development or production mode
const env = loadEnv('development', process.cwd(), ['VITE_']);
console.log('Env:', env);
console.log('API URL:', env.VITE_API_URL); // Prints the environment variables to the server console
console.log("******************************");
console.log('Current working directory:', process.cwd()); // Prints the working directory to the server console
console.log("******************************");
export default defineConfig({
plugins: [react()],
server: {
host: '0.0.0.0',
port: 5173,
},
build: {
target: 'esnext',
minify: 'esbuild',
lib: {
entry: './src/index.tsx',
formats: ['es'],
},
},
});
vite-env.d.ts file:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
readonly VITE_IP_SERVER_GOCHAT: string;
readonly VITE_PORT_SERVER_GOCHAT: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
What’s happening:
When I run npm run dev, the log shows that the environment variables are not loading correctly. The env object is empty, and the environment variables are undefined, meaning that they are not being loaded properly from the .env file.
Here’s the log I get in the console:
Env: {}
API URL: undefined
******************************
Current working directory: /home/jogugil/jogugil_projects/gochat/web
******************************
VITE v4.5.5 ready in 234 ms
➜ Local: http://localhost:5173/
➜ Network: http://10.255.255.254:5173/
➜ Network: http://172.25.157.234:5173/
I’ve tried several solutions, but I can’t get the environment variables to load properly. Can anyone help me fix this?
In Vite you should use import.meta.env
and not process.env
because it will run in the browser.
Example :
console.log('API URL:', import.meta.env.VITE_API_URL);
1