Sub topic 17
Using environment variables safely
This chapter assumes you can scaffold a Vite project, run npm run dev and npm run build, and read a vite.config.js file. It covers how Vite exposes configuration values to your React code and why that is not a safe place for secrets.
What environment variables are for
An environment variable is a named value that lives outside your source code. Apps use them for settings that change between machines, such as the URL of an API in development and in production. Keeping these values out of your components means you can change them without editing code.
Vite reads them from .env files in the project root and exposes them to client code through import.meta.env.
The VITE_ prefix
Vite exposes only variables whose names start with VITE_. Everything else stays out of the bundle.
Create a .env file next to package.json:
VITE_API_URL=https://api.example.com
DB_PASSWORD=not-for-the-browserThen read the value in your code:
// .env file contains: VITE_API_URL=https://api.example.com
const apiUrl = import.meta.env.VITE_API_URL
console.log(apiUrl)import.meta.env.VITE_API_URL gives you the URL. import.meta.env.DB_PASSWORD is undefined, because it has no prefix.
Which file is loaded when
Vite picks files by mode. The dev server runs in development mode and npm run build runs in production mode.
| File | Loaded when |
|---|---|
| `.env` | Always |
| `.env.development` | Dev server only |
| `.env.production` | Build only |
| `.env.local` | Always, and kept out of git by default |
Mode-specific files override .env. Restart the dev server after you edit a file, because Vite reads these files at startup.
The safety rule
Vite does not hide VITE_ values. At build time it replaces each import.meta.env.VITE_... expression with the literal value. Anyone can open the browser's developer tools and read it.
Safe examples are a public API base URL, a feature flag, or a public analytics ID. Unsafe examples are a payment secret key or a database password.
Common errors
- Value is
undefined. The name is missing theVITE_prefix, or the file is not in the project root. - Edit has no effect. You did not restart the dev server.
- A build still has the old value. Values are fixed at build time, so run
npm run buildagain after changing them. - Secrets committed to git. Add
.env.localto.gitignoreif it is not already there, and keep real values out of shared files.
Exercise
Your .env file contains STRIPE_SECRET_KEY=sk_live_abc and VITE_SHOP_NAME=Corner Store. Which of these can your React code read through import.meta.env, and should the secret key be placed in a VITE_ variable to make it readable?
Show answer
Only import.meta.env.VITE_SHOP_NAME is readable. STRIPE_SECRET_KEY is undefined in client code, which protects it. You should not rename it with a VITE_ prefix, because the value would be inlined into the bundle and visible to every user. Keep the secret on a server and have your app call that server.