Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 16 / Topic 8 of 9

Environment variables: import.meta.env.VITE_*

examples/07_env_vars/ApiBaseUrl.jsx reads one environment variable, with a fallback for when it's missing:

// examples/07_env_vars/ApiBaseUrl.jsx
const DEFAULT_API_BASE_URL = "https://api.example.local";

export function ApiBaseUrl() {
  const base = import.meta.env.VITE_API_BASE_URL ?? DEFAULT_API_BASE_URL;
  return <p>API base: {base}</p>;
}

Vite's convention, confirmed against the installed [email protected] dev server and build, not assumed: only variables whose name starts with VITE_ are exposed to client code through import.meta.env - anything without that prefix (a database password, a private API key sitting in the same .env file) is invisible to import.meta.env entirely, on purpose, so it can never end up readable in a browser's dev tools or shipped inside a built JS bundle just because a component happened to read import.meta.env.SOMETHING. A real project keeps these in a .env file (checked in, for defaults safe to share) and a .env.local file (git-ignored, for a developer's own machine-specific overrides) at the project root - Vite loads both automatically and merges them, .env.local winning. ApiBaseUrl.test.jsx really proves the fallback path (no var set, renders the default) and the override path (import.meta.env.VITE_API_BASE_URL set to a different value, renders that instead) - and it proves something specific to how Vitest runs this code, confirmed by actually running the test rather than assumed from the docs: Vitest does not statically replace import.meta.env.VITE_X references at transform time the way a production Vite build does, so a test can mutate import.meta.env.VITE_API_BASE_URL directly, read it back inside the very next render, and clean it up with delete import.meta.env.VITE_API_BASE_URL in afterEach so the mutation never leaks into a later test.

⚠️ A VITE_-prefixed variable is exposed to every visitor's browser, baked straight into the built JS bundle - it is not a secret, and it was never meant to be one. An API key that must stay secret belongs on a server your client code talks to, never in a VITE_* variable; the VITE_ prefix is a safety rail that quietly keeps non-prefixed vars out of the bundle, not a vault for making a sensitive one safe to ship.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide