Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 23.2 — Environment Variables and Configuration
React · Example 2 of 3

Which .env file wins?

This copies the order a real Vite 8 build used when tested with five variables spread over .env, .env.local, .env.staging, .env.staging.local and the shell. Notice the surprise in a real team: .env.local on one developer's laptop turns chat on in their production build, but not in CI's. Build releases in CI, never on a laptop.

Configuration such as an API address or a feature switch reaches a React app either at build time, when the build tool pastes VITE_ or NEXT_PUBLIC_ values into the bundle, or at runtime, when the app loads a config file as it starts; anything that reaches the browser is public, so secrets never belong there.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a config.js module for a Vite app that reads VITE_API_URL and VITE_FEATURE_CHAT, throws a clear error if the URL is missing, and exports { apiUrl, chatEnabled }.

02

Write the package.json scripts to build the same app for staging and production with Vite modes.

Explain it without notes

01

What is the difference between build-time and runtime configuration in a React app?

02

Why do Vite and Next.js require the VITE_ and NEXT_PUBLIC_ prefixes?

03

In what order does Vite load .env files, and which wins?

04

How would you keep an API secret safe in a React app that needs to call that API?

Which .env file wins?

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

production: {"VITE_API_URL":"https://api.example.com","VITE_FEATURE_CHAT":"on","VITE_SENTRY_ENV":"production"}
staging: {"VITE_API_URL":"https://staging-api.example.com","VITE_FEATURE_CHAT":"on","VITE_SENTRY_ENV":"staging"}
staging + shell: {"VITE_API_URL":"https://staging-api.example.com","VITE_FEATURE_CHAT":"off","VITE_SENTRY_ENV":"staging"}