gotchaModerate
Environment variables undefined in client-side code (Vite, Next.js, CRA)
Viewed 0 times
VITE_NEXT_PUBLIC_REACT_APP_process.envimport.meta.envundefineddotenv
browsernodejs
Error Messages
Problem
Environment variables from .env are accessible on the server but undefined in client-side/browser code. process.env.MY_VAR returns undefined in React components.
Solution
Client-side env vars require framework-specific prefixes: Vite: VITE_ prefix, accessed via import.meta.env.VITE_MY_VAR. Next.js: NEXT_PUBLIC_ prefix. Create React App: REACT_APP_ prefix. Without the prefix, the bundler excludes them from the client bundle to prevent leaking secrets. After adding the prefix, restart the dev server — env vars are read at build time. Never prefix secret keys.
Why
Bundlers substitute env vars at build time via string replacement. Only prefixed vars are included to prevent shipping secrets to the browser.
Revisions (0)
No revisions yet.