Sub topic 17
Using environment variables safely
This chapter assumes you can scaffold a Vite React project, run npm run dev and npm run build, and read vite.config.js. You should also know what a bundle is. The chapter covers how Vite exposes configuration values to your code, which values end up in the browser, and the mistakes that leak 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 or stages, such as the base URL of an API. You can then use one codebase for development, staging and production without editing source files.
In a browser app there is one fact that shapes everything else: the code you ship runs on the user's machine. Anyone can open the developer tools, read your JavaScript bundle and see every value inside it. An environment variable in a Vite app is therefore a build-time setting, not a secret store.
How Vite exposes variables
Vite reads variables when the dev server starts or when you run a build. It then makes some of them available to client code through import.meta.env. Vite replaces those references with literal values while it builds the bundle.
Only variables whose names start with VITE_ are exposed. Everything else stays out of your client code.
// .env file contains: VITE_API_URL=https://api.example.com
const apiUrl = import.meta.env.VITE_API_URL
console.log(apiUrl)Vite also provides a few built-in values on import.meta.env:
| Name | Meaning |
|---|---|
| `import.meta.env.MODE` | The current mode, such as `development` or `production`. |
| `import.meta.env.DEV` | `true` when running the dev server. |
| `import.meta.env.PROD` | `true` in a production build. |
| `import.meta.env.BASE_URL` | The base path the app is served from. |
All values read from .env files are strings. The text false is a non-empty string, so if (import.meta.env.VITE_FEATURE) is true even when the file says VITE_FEATURE=false. Compare against the string instead.
const featureOn = import.meta.env.VITE_FEATURE === 'true'Where the values come from: .env files
Vite loads variables from files in the project root, next to package.json. A file is loaded depending on the mode.
| File | Loaded when |
|---|---|
| `.env` | Always. |
| `.env.local` | Always, and meant to stay out of Git. |
| `.env.development` | In development mode (`npm run dev`). |
| `.env.production` | In production mode (`npm run build`). |
| `.env.[mode].local` | Only in that mode, and meant to stay out of Git. |
When the same name appears in several files, the more specific file wins. A mode file overrides .env, and a .local file overrides its non-local counterpart. Variables already set in the shell when you run the command take priority over all files.
A typical setup looks like this:
# .env (committed: safe defaults, no secrets)
VITE_API_URL=http://localhost:3000
# .env.production (committed: public production settings)
VITE_API_URL=https://api.example.com
# .env.local (not committed: personal overrides)
VITE_API_URL=http://localhost:4000Restart the dev server after you change a .env file. Vite reads these files at startup, so edits are not picked up while it runs.
What is safe to put behind VITE_
The prefix is a guard against accidents. It stops a variable such as DB_PASSWORD from being bundled just because it exists on your machine. It does not make a VITE_ variable private. Anything with the prefix is copied into the bundle as plain text.
Safe to expose:
- Public API base URLs.
- Feature flags.
- Public identifiers designed for browsers, such as a publishable payment key or an analytics ID.
- The app's display name or version.
Never expose:
- Database passwords and connection strings.
- Private API keys and signing secrets.
- Tokens that grant write access or access to other users' data.
- Any credential you would not paste into a public web page.
If your app needs to call a service that requires a private key, put a small backend or serverless function between them. The browser sends a request to your backend. The backend adds the key and forwards the call. The key never reaches the client.
Using variables well in code
Read each variable in one place, then import the result. This gives you one spot to validate values and set defaults.
// src/config.js
const apiUrl = import.meta.env.VITE_API_URL
if (!apiUrl) {
throw new Error('VITE_API_URL is not set. Add it to your .env file.')
}
export const config = {
apiUrl,
featureOn: import.meta.env.VITE_FEATURE === 'true',
}// src/Status.jsx
import { config } from './config.js'
function Status() {
return <p>Talking to {config.apiUrl}</p>
}
export default StatusFailing early with a clear message is better than sending requests to undefined/users and debugging a 404.
Changing the prefix and keeping types
You can change which prefix is exposed with the envPrefix option in vite.config.js. Avoid setting it to an empty string, because that would expose every variable in the environment.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
envPrefix: 'VITE_',
})Common errors
- The variable is
undefined. Check that the name starts withVITE_, the file is in the project root, and you restarted the dev server. - Using
process.env. In Vite client code,process.env.VITE_API_URLis not defined in the browser. Useimport.meta.env. - Treating values as booleans or numbers. They are strings. Convert them with
=== 'true'orNumber(...). - Changing a value after building. Vite inlines values during
npm run build. Editing.envafterward changes nothing indist. Rebuild, or load runtime settings from a file or endpoint the app fetches when it starts. - Committing secrets. Add
*.localto.gitignore(the Vite template usually does) and never commit real credentials in any.envfile. - Assuming production hides the values. Run
npm run build, then search thedistfolder for one of your variable values. You will find it.
npm run build
grep -r "api.example.com" distExercises
Exercise
Your .env file contains API_KEY=abc123 and VITE_API_URL=https://api.example.com. In a component you log import.meta.env.API_KEY and import.meta.env.VITE_API_URL. What does each log, and why?
Show answer
import.meta.env.API_KEY logs undefined because Vite only exposes variables that start with VITE_. import.meta.env.VITE_API_URL logs https://api.example.com. The second value is also visible to anyone who reads your built JavaScript.
Exercise
A teammate adds VITE_STRIPE_SECRET_KEY=sk_live_... to .env.production so the checkout page can create charges directly from the browser. What is wrong, and what should they do instead?
Show answer
The VITE_ prefix puts the value into the production bundle, so anyone can read the secret key and use it. They should keep the secret key in a server environment, create the charge in a backend endpoint, and have the browser call that endpoint. A publishable key, which Stripe designs for browsers, can stay in a VITE_ variable.
Exercise
You set VITE_DEBUG=false and write if (import.meta.env.VITE_DEBUG) { showDebugPanel() }. The panel still appears. Why, and how do you fix it?
Show answer
Env values are strings, and the string false is truthy. Compare explicitly: if (import.meta.env.VITE_DEBUG === 'true').