Environment Variables and Configuration
Manage per-environment configuration safely, understanding the difference between build-time public variables and server-only secrets.
Intermediate · about 2 hours · difficulty 2/5
Learn first: Deploying Frontend Apps, Schema Validation with Zod
Apps behave differently in development, preview and production: different API URLs, analytics keys and feature flags. Environment variables carry this configuration, and frontend developers must understand one crucial rule: anything bundled into client JavaScript is public.
Public vs server-only
- Build tools only expose variables with a prefix to client code:
VITE_in Vite (import.meta.env.VITE_API_URL),NEXT_PUBLIC_in Next.js,PUBLIC_in Astro and SvelteKit. These are inlined at build time and visible to anyone who opens DevTools. - Unprefixed variables stay on the server (Next.js server components, route handlers, SvelteKit server loads). This is where API secrets, database URLs and private keys belong.
- If the browser needs data that requires a secret, call your own server or a serverless function that holds the secret.
Files and environments
.envfor defaults,.env.localfor personal overrides (git-ignored), and mode-specific files like.env.production.- Commit a
.env.exampledocumenting required variables without real values. - Set real values in your hosting dashboard per environment (production, preview, development) and in CI secrets.
- Because public variables are baked in at build time, changing them requires a rebuild.
Safety and validation
- Validate variables at startup with a schema (Zod) so a missing value fails the build, not a user session.
- Type them (
vite-env.d.ts) for autocomplete. - If a secret ever lands in a client bundle or Git history, treat it as leaked: rotate it.
Feature flags
Runtime flags (LaunchDarkly, GrowthBook, PostHog, or a simple config endpoint) let you ship code dark and enable it gradually without redeploying.
Good enough to move on
You can configure an app for three environments, keep secrets server-side, validate and type variables, and explain why a VITE_ variable is not secret.
Key concepts
- Build-time public variables
- Server-only secrets
- VITE_ and NEXT_PUBLIC_ prefixes
- .env files and .env.example
- Per-environment values on the host
- Validating env vars with a schema
- Rotating leaked secrets
- Feature flags
Mini project
Configure your deployed app with separate API URLs for development, preview and production, move a third-party API key behind a serverless function, and fail the build when a required variable is missing.
Check yourself
A teammate puts a payment provider's secret key in VITE_PAYMENT_SECRET. What is the problem and what should they do instead?
Free resources
- Env Variables and Modes (Vite)
- Environment Variables in Next.js (Vercel)