Skip to main content

5 posts tagged with "Vite"

View all tags

Vite Env Variable Undefined? It Needs the VITE_ Prefix

Β· 5 min read

You set API_URL=http://localhost:3005 in a Vite project's .env, but import.meta.env.API_URL logs undefined in the browser, and every API request goes to the wrong address.

Encountered this while building an AI Agent SaaS platform for a client β€” recording the root cause and the fix.

TL;DR​

Vite exposes only VITE_-prefixed environment variables to client code β€” a security design that keeps server secrets out of the browser bundle.

# ❌ never exposed to the frontend
API_URL=http://localhost:3005

# βœ… exposed to the frontend
VITE_API_URL=http://localhost:3005

Access it as import.meta.env.VITE_API_URL. TypeScript projects should add one more step: an env.d.ts declaration for proper autocomplete.

Symptoms​

Two typical presentations:

Symptom 1: the variable is undefined

// .env: API_URL=http://localhost:3005
console.log(import.meta.env.API_URL) // undefined
console.log(import.meta.env) // BASE_URL, MODE, PROD... are all there β€” just not yours

The .env file clearly loaded (MODE, PROD and the other built-ins are present), so this is not a loading failure β€” the exposure rule filtered your variable out.

Symptom 2: prefix added, access name mistyped

// .env: VITE_API_URL=...
const url = import.meta.env.VITE_APIURL // undefined β€” case must match exactly

A separate note: "environment variable reads undefined" on the Node.js server side has a different common cause (dotenv load order) β€” see Node.js env loaded undefined: dotenv import order. Don't mix the two investigations.

Root Cause: The Prefix Rule Is a Security Boundary​

Vite's design problem: .env files typically hold two kinds of values β€” public config the frontend needs (an API base URL) and values that must never reach a browser (database URLs, third-party API keys). Exposing everything means one oversight puts a secret into a publicly served static bundle.

So Vite draws a hard line: only VITE_-prefixed variables appear in import.meta.env. Everything else is visible only in vite.config.ts (the Node side) via loadEnv.

The exposure mechanism matters too: static replacement at build time. Vite inlines import.meta.env.VITE_API_URL as a string literal during the build; at runtime there is no "read the environment" step. Two consequences:

  1. The value appears in plain text inside the shipped JS β€” a VITE_ variable is public by nature
  2. Changing environment at runtime (container env, system variables) never affects an already-built bundle β€” switching environments requires a rebuild, or a runtime-injected config (e.g. window.__CONFIG__)

The Fix: Prefix + Type Declaration​

Step 1: add the VITE_ prefix in .env. Keep the name semantic; the prefix is only an exposure marker:

# .env
VITE_API_URL=http://localhost:3005

Step 2: read it through one config module, not scattered import.meta.env calls in components:

// src/config.ts
export const API_URL = import.meta.env.VITE_API_URL

Step 3 (TypeScript projects): declare the types in src/env.d.ts for full autocomplete:

/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_API_URL: string
}

interface ImportMeta {
readonly env: ImportMetaEnv
}

Separate dev and production values with mode files β€” Vite picks the right one automatically:

.env.development    # dev server
.env.production # npm run build
.env # loaded in both β€” shared config goes here

After editing any .env file, restart the dev server β€” env files load once at startup, and hot reload does not refresh them. This is the second most common "I changed it but nothing happened" cause.

Watch out

A VITE_ variable is public information: its value is inlined into the client bundle in plain text. API base URLs and feature flags are fine; database connection strings and third-party secrets are not β€” those stay in server-side environment variables. When the frontend needs protected config, serve it from an API endpoint instead of .env.

FAQ​

Where do Vite environment variables live?​

In the .env family at the project root: .env loads in both modes, .env.development only for the dev server, .env.production only during builds. After editing any of them you must restart the dev server β€” Vite loads env files once at startup, and hot reload does not refresh them.

Can I put secrets behind the VITE_ prefix?​

No. VITE_ variables are statically inlined into the client bundle at build time β€” anyone can read them in the page source. The prefix exists to separate publishable config (API base URLs, feature flags) from server-only secrets. Secrets belong in server-side environment variables only.

What is the difference between process.env and import.meta.env in Vite?​

import.meta.env is the browser-side API β€” Vite statically replaces VITE_-prefixed keys into it. process.env is a Node.js API, available only inside vite.config.ts and SSR contexts. Writing process.env.XXX in frontend code is always undefined after build.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Vite Proxy Works in Dev but 404 in Production? Add Nginx

Β· 5 min read

A Vite project works perfectly in local development. After npm run build and deploying to the server, pages load fine, but every /api request returns 404 β€” or something sneakier: the response is index.html, and the frontend crashes parsing HTML as JSON.

Encountered this while building an AI Agent SaaS platform for a client with a separated frontend/backend deployment β€” recording the root cause and the fix.

TL;DR​

server.proxy in vite.config.ts belongs to the dev server only. npm run build produces plain static files with no proxy layer at all; in production, Nginx must take over /api:

location /api {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

Placed outside the reach of the SPA fallback (try_files ... /index.html), validated with nginx -t, applied with nginx -s reload.

Symptoms​

Two presentations, one root cause:

Presentation 1: plain 404

GET https://example.com/api/agents  β†’ 404 Not Found

Presentation 2: index.html comes back (sneakier)

GET /api/agents  β†’ 200 OK, but the body is <!DOCTYPE html>...
Frontend fails with: Unexpected token '<' in JSON

The second one is the SPA fallback catching the request: Nginx finds no static file at /api/agents, and try_files $uri /index.html bounces it to the frontend entry page. The status code is even a green 200 β€” it only blows up when the frontend parses the body, which makes it look like "the request succeeded".

Root Cause: proxy Is a Dev-Server Runtime Feature​

This block in vite.config.ts:

// vite.config.ts
export default defineConfig({
server: {
proxy: {
'/api': 'http://127.0.0.1:3000',
},
},
})

works in exactly one context: the dev server started by npm run dev. That dev server is a Node process, and server.proxy is forwarding middleware inside it β€” the browser requests localhost:5173/api/agents, the dev server passes it to 127.0.0.1:3000, and brings the response back.

After npm run build, the output is a pile of static files in dist/, and the browser fetches them straight from Nginx β€” there is no Vite process anywhere in that chain, and the server.proxy config stays behind in vite.config.ts; it never ships with the build.

So in production the request path is: browser β†’ Nginx β†’ ?. Nginx matches locations; with no /api rule, no static file exists at /api/agents, so it either 404s or falls through to index.html via the SPA fallback β€” the two presentations, explained.

The Fix: Let Nginx Own the Production Proxy​

Step 1: add a proxying location to the server block.

server {
listen 80;
server_name example.com;
root /var/www/app/dist;

# API proxy: prefix match, wins over the SPA fallback
location /api {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# SPA fallback: everything else goes to the frontend entry
location / {
try_files $uri $uri/ /index.html;
}
}

Two points:

  • proxy_pass points at the real backend address and port (swap the example's 3000 for yours); /api-prefixed requests are forwarded as-is, so backend routes must carry the /api prefix
  • Nginx prefix locations match by longest prefix, so /api naturally beats / β€” no ordering tricks needed; just make sure your longest API common prefix is covered

Step 2: verify, then serve traffic.

nginx -t          # syntax check
nginx -s reload # graceful reload

# Smoke test: should return backend data, not HTML
curl -i https://example.com/api/health

JSON with Content-Type: application/json means the proxy is live; text/html means the fallback is still catching requests.

A side benefit: once both apps share a domain through the reverse proxy, the CORS problem you dodged in dev with Vite proxy disappears in production too β€” no CORS headers to configure.

This post and Frontend Deploy Looks Outdated? Nginx Cache and Build Output Checks are companion reads: that one covers "the deployed code is stale", this one covers "the API has no proxy layer in production". Check both and deployment-related 404s are pretty much exhausted.

Watch out

The location path must match the backend route prefix exactly. If backend routes live at /api/agents but Nginx proxies /apis, or proxy_pass ends with a stray / (which triggers path rewriting β€” /api/agents arrives at the backend as /agents), you get a fresh new 404. After any change, curl -i one real endpoint and check the response headers before sending traffic.

FAQ​

Does Vite proxy work in production?​

No. server.proxy is a runtime middleware of the dev server β€” it exists when you run npm run dev. A production build produces plain static files served by Nginx (or any web server), with no Vite process and no proxy layer. The production equivalent is an Nginx location block with proxy_pass, which typically adds 2 proxy_set_header lines and a reload.

Why is the Vite proxy not working after build?​

Because the proxy config never ships with the build. After deploying, /api requests hit Nginx directly; with no /api location rule they either 404 or get caught by the SPA fallback (try_files ... /index.html), returning HTML with a 200 status that breaks JSON parsing on the frontend. Add an /api proxy location and reload Nginx.

How do I route API requests through Nginx for a Vite app?​

Inside the server block add: location /api { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } β€” then nginx -t and nginx -s reload. Verify with curl -i https://example.com/api/health: a JSON content type means the proxy is live, text/html means the SPA fallback is still catching it.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Chrome Extension Processing Messages Twice After Hot Reload? WXT HMR Stacks Listeners

Β· 2 min read

Encountered this issue while building an e-commerce data collection Chrome extension for a client. Here's the root cause and solution.

TL;DR​

WXT framework's HMR re-executes content scripts on file changes but doesn't clean up old window.addEventListener('message', ...) handlers. Each hot reload adds another listener β€” every postMessage fires all instances.

Fix: Before registering a new listener, retrieve the old one from a window variable and call removeEventListener.

Problem​

Browser console showed each message caught by two different instances:

content.js:114 [CCL] CCL_SHOP_REPORT_DAILY daily caught - instance: nxctn6
content.js:2 [CCL] CCL_SHOP_REPORT_DAILY daily caught - instance: t6jce7

Every postMessage processed twice, causing duplicate requests to the backend.

Root Cause​

WXT (a Vite-based Chrome extension framework) in dev mode triggers HMR on content script changes:

  1. The new content script module loads and executes
  2. A new window.addEventListener('message', messageListener) is registered
  3. The old listener function remains in memory β€” HMR doesn't clean up DOM event listeners

Result: multiple independent message listeners on window, each postMessage triggering all of them.

Solution​

At the content script entry point, remove the old listener before registering the new one:

const instanceId = Math.random().toString(36).slice(2, 8);

// Retrieve old listener reference
const prevListener = (window as any).__cclMessageListener;
if (prevListener) {
window.removeEventListener('message', prevListener);
}

// Define new listener
const messageListener = (event: MessageEvent) => {
// ... handling logic
};

// Store current reference (for next HMR cycle)
(window as any).__cclMessageListener = messageListener;

// Register
window.addEventListener('message', messageListener);

Key insight: removeEventListener requires the exact same function reference as addEventListener. By storing the function on window, the next HMR cycle can retrieve and remove the old one correctly. This ensures only one active message listener exists at any time, regardless of how many hot reloads occur.

If you're also seeing postMessage data leaking to third-party iframes or empty collected data due to cookie format mismatch, check those issues too.

Note

  • This issue isn't limited to WXT β€” any framework that hot-reloads content scripts (Plasmo, CRXJS, etc.) can encounter it
  • window variables persist until page refresh; HMR only replaces script modules, not window properties
  • Production builds don't have this issue (content script loads once), but it causes hard-to-debug duplicate requests during development