Mastering Environment Variables in Vite

0. Offical Doc

https://vite.dev/guide/env-and-mode

Variable Naming Convention

Vite has a specific convention for exposing variables to your client-side code:

  • Only variables prefixed with VITE_ are exposed to your Vite-processed code
  • This is a security feature to prevent accidentally exposing sensitive variables

1. Practical Implementation

1. Creating Environment Files

First, create an .env file in your project root:

1
2
3
4
5
6
# This will be available in all environments
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My Awesome App

# This won't be exposed to the client
SECRET_API_KEY=sensitive-data-not-exposed

2. Accessing Environment Variables in Your Code

Now you can use these variables in your application:

1
2
3
4
5
6
7
8
9
10
11
12
// Access the API URL
const apiUrl = import.meta.env.VITE_API_URL;

// Use the app title
document.title = import.meta.env.VITE_APP_TITLE;

// Parse JSON values
const featureFlags = JSON.parse(import.meta.env.VITE_FEATURE_FLAGS);

console.log(`API URL: ${apiUrl}`);
console.log(`Is development: ${import.meta.env.DEV}`);
console.log(`New UI enabled: ${featureFlags.newUI}`);

3. Type Definitions for TypeScript Projects

If you’re using TypeScript, you’ll want proper type definitions. Create a env.d.ts file:

1
2
3
4
5
6
7
8
9
10
11
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_APP_TITLE: string
readonly VITE_LOG_LEVEL: 'debug' | 'info' | 'warn' | 'error'
readonly VITE_FEATURE_FLAGS: string
// add more env variables here
}

interface ImportMeta {
readonly env: ImportMetaEnv
}

Mastering Environment Variables in Vite
https://www.hardyhu.cn/2025/02/20/Mastering-Environment-Variables-in-Vite/
Author
John Doe
Posted on
February 20, 2025
Licensed under