How to Load Environment Variables from .env File Using Vite

Nov 23, 2025 · Programming · 10 views · 7.8

Keywords: Vite | Environment Variables | .env File

Abstract: This article provides a comprehensive guide on loading environment variables from .env files in Vite projects. It explains Vite's security mechanisms that require VITE_ prefix for client-side accessibility, demonstrates the use of loadEnv() function in configuration files, and offers complete code examples and best practices for effective environment variable management.

Environment Variable Loading Mechanism

In Vite projects, environment variable handling follows specific security rules. To prevent accidental leakage of sensitive information to the client, Vite only exposes environment variables prefixed with VITE_ to Vite-processed code. This means if you define TEST_VAR=123F in your .env file, accessing it directly via import.meta.env.TEST_VAR will return undefined.

Proper Environment Variable Naming

To make environment variables accessible in client-side code, you must use the VITE_ prefix. For example, modify your .env file to:

VITE_TEST_VAR=123F

Then access the variable in your JavaScript code using import.meta.env.VITE_TEST_VAR.

Environment Variable Handling in Configuration Files

For configuration files like vite.config.js, which run in the Node.js environment, a different approach is needed. Vite provides the loadEnv() function for this purpose:

import { defineConfig, loadEnv } from 'vite';

export default ({ mode }) => {
    // Load app-level env vars to node-level env vars
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};
    
    return defineConfig({
        // Access env vars here using process.env.TEST_VAR
    });
}

Special Handling in SvelteKit Projects

In SvelteKit projects, environment variable loading follows a similar pattern but requires integration with SvelteKit-specific configuration:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig, loadEnv } from 'vite';

/** @type {import('vite').UserConfig} */
export default ({ mode }) => {
    // Extends 'process.env.*' with VITE_*-variables
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};
    return defineConfig({
        plugins: [sveltekit()]
    }); 
};

Common Issues and Solutions

During development, you might encounter issues with environment variable loading. Ensure your .env file is located in the project root directory, not in the src directory. The development server needs to be restarted to recognize new environment variables - execute npm run dev to restart the service. Always remember to use the VITE_ prefix when defining environment variables that need to be accessed on the client side.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.