Course contentsShow
← Web Development
Lesson 1378 of 2,98225. Build Tools and BundlersFree lesson

Environment Variables in Vite

Using .env files and the import.meta.env object to manage environment-specific configuration.

Environment Variables in Vite

You'll learn how to manage different configurations for development, staging, and production using Vite's built-in environment variable system.

What Are Environment Variables in Vite?

Environment variables let you store configuration values outside your code—like API URLs, feature flags, or API keys—that change depending on where your app runs. Instead of hardcoding https://api.myapp.com directly in your JavaScript, you reference a variable that holds different values in development versus production.

Think of environment variables like placeholders in a form letter: the template stays the same, but the actual values get filled in based on who's receiving it (which environment you're in).

Using .env Files

Vite automatically loads variables from .env files in your project root:

VITE_API_URL=https://api.example.com
VITE_ENABLE_ANALYTICS=true

Critical rule: Only variables prefixed with VITE_ are exposed to your client-side code. This prevents accidentally leaking sensitive server-only secrets.

You can create environment-specific files:

  • .env.development - loaded during dev server
  • .env.production - loaded during build
  • .env.local - local overrides (git-ignored)

Accessing Variables with import.meta.env

Inside your application code, access these variables through the import.meta.env object:

const apiUrl = import.meta.env.VITE_API_URL;
const isDev = import.meta.env.DEV; // built-in boolean
const isProd = import.meta.env.PROD; // built-in boolean

Vite replaces these references at build time, so they become static values in your production bundle.

Key Takeaway: Vite's .env files and import.meta.env object provide a secure, environment-aware way to manage configuration—just remember the VITE_ prefix requirement for client-side exposure.