Environment Variables with import.meta.env
What you'll learn: How to safely access configuration values in your Vite + React project without hardcoding secrets.
The Core Idea
When building React apps with Vite, you often need configuration values that change between environments (like API URLs for development vs. production, or feature flags). Instead of hardcoding these values directly in your code, you store them as environment variables.
In Vite projects, you access these variables through import.meta.env — not process.env like you might see in older Create React App tutorials.
How It Works
Think of environment variables like a secure locker outside your codebase. You keep sensitive or environment-specific information there, and your app retrieves it at build time.
The VITE_ Prefix Rule
Here's the catch: only variables prefixed with VITE_ are exposed to your client code. This is a safety feature preventing you from accidentally leaking server secrets into your browser bundle.
Create a .env file in your project root:
VITE_API_URL=https://api.example.com
VITE_FEATURE_FLAG=true
Access them in your React components:
function App() {
const apiUrl = import.meta.env.VITE_API_URL;
// Use apiUrl to fetch data
}
Why This Matters
This pattern lets you keep one codebase but configure it differently for development, staging, and production without changing a single line of code. You simply swap out the .env file.
Key Takeaway: In Vite + React projects, use import.meta.env.VITE_YOUR_VAR to access environment variables — the VITE_ prefix is mandatory for security, and this replaces the old process.env approach from Create React App.