import.meta.env.VITE_API_URL is undefined in production: why Vite env variables stop working after deploy
import.meta.env.VITE_API_URL is undefined in production when Vite did not have the variable at the moment it built the site: Vite writes the values into the files at build time, so a variable set only where the site runs is never seen. The other usual causes: a name without the VITE_ prefix, a .env.local file that is ignored by git and never reaches the build server, a value kept in .env.development, and process.env in client code. Set the variable where the build runs, with the prefix, and build again.
By Livops team, the people who build and run LivopsUpdated
What people see, in the browser console of the deployed site:
console.log(import.meta.env.VITE_API_URL); // undefined
Or, more often, no log at all, just failed requests to an address like https://shop.example.com/undefined/products, because the code builds its URLs like this:
fetch(`${import.meta.env.VITE_API_URL}/products`);
The same code works with npm run dev on your machine. This page explains when Vite reads env variables and why that is the whole story, lists the causes from most to least common with the fix for each, and shows how to check the built files before you deploy again.
What does it mean?
Vite exposes env variables under import.meta.env, and in a production build it statically replaces them: the value is written into the JavaScript files at build time[1]. There is no lookup when the page runs. And a variable Vite did not expose, such as import.meta.env.NON_EXISTENT, is replaced with undefined[1].
So undefined in production means one thing: at the moment vite build ran, Vite did not have that variable under that name. Every cause below is a way that happens.
Only variables whose names start with VITE_ reach client code[1]. Vite’s own example[1]:
# .env
VITE_SOME_KEY=123
DB_PASSWORD=foobar
console.log(import.meta.env.VITE_SOME_KEY); // "123"
console.log(import.meta.env.DB_PASSWORD); // undefined
Causes, most common first
1. The variable is set where the site runs, not where it builds
You add VITE_API_URL on the server, in the container, or in your host’s settings after the site was built, and nothing changes. The built files already contain whatever value Vite had at build time[1], which was none.
Fix: the variable must exist in the environment of the vite build command, and you must build again after every change. Variables that already exist when Vite is executed have the highest priority and are not overwritten by .env files[1], so this works on any build server:
VITE_API_URL=https://api.example.com npm run build
If you build in a Dockerfile, the value has to reach the step that runs the build, not only the container at run time:
ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL
RUN npm run build
Restarting a site never helps here; only a new build does.
2. The name has no VITE_ prefix
API_URL=... or REACT_APP_API_URL=... is set, but the code reads it through import.meta.env. Vite exposes only variables that start with envPrefix, and its default is VITE_[2].
Fix: rename the variable to VITE_API_URL, in the code and wherever it is set. If you are moving from Create React App and want to keep the old names for now, envPrefix accepts a string or a list[2]:
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
envPrefix: ["VITE_", "REACT_APP_"],
});
Do not set envPrefix to '': it would expose all your env variables, and Vite throws an error when it sees it[2]. To expose a single unprefixed variable, Vite’s docs suggest define[2]:
define: {
"import.meta.env.ENV_VARIABLE": JSON.stringify(process.env.ENV_VARIABLE),
},
3. The .env file never reaches the build server
The value lives in .env.local on your machine. Vite loads .env.local in all cases, but it is meant to be ignored by git[1], and Vite tells you to add *.local to .gitignore[1]. Many projects ignore .env too. A build server that clones the repository gets neither file, so the variable does not exist there.
Fix: set the variable in your host’s build settings (cause 1), or, for values that are not secret, commit a .env.production file:
# .env.production, committed
VITE_API_URL=https://api.example.com
Whatever you put in a VITE_ variable is public anyway: the values are bundled into your source code at build time, and Vite’s docs say they should not contain sensitive information such as API keys[1].
In a monorepo, also check where the file is. Vite loads .env files from envDir, which defaults to the project root[2], so a .env one folder up, at the repository root, is not read unless envDir points there.
4. The value is in a file for another mode
The files Vite loads[1]:
| File | Loaded |
|---|---|
.env |
in all cases |
.env.local |
in all cases, ignored by git |
.env.[mode] |
only in that mode |
.env.[mode].local |
only in that mode, ignored by git |
vite (the dev server) runs in development mode and vite build runs in production mode[1]. So a value kept only in .env.development works in npm run dev and is undefined in the build, and vite build reads .env.production if there is one[1].
Fix: put production values in .env.production or in the build environment. A mode-specific file wins over the generic .env[1]. For a staging build, vite build --mode staging loads .env.staging[1]; check import.meta.env.MODE to see which mode a build used[1].
On your own machine, .env files are loaded when Vite starts, so restart the dev server after you change one[1].
5. The code reads process.env
Code copied from a Node.js project or from Create React App reads process.env.VITE_API_URL or process.env.REACT_APP_API_URL. Vite exposes env variables to your app under import.meta.env[1]; read them there:
// before
const api = process.env.REACT_APP_API_URL;
// after
const api = import.meta.env.VITE_API_URL;
The opposite trap is in vite.config.js itself. While the config file runs, process.env holds only what already exists in the process environment: Vite loads .env files after the config is resolved, so values from .env, .env.local or .env.[mode] are not in process.env there[3]. If the config needs them, load them with loadEnv[3]:
// vite.config.js
import { defineConfig, loadEnv } from "vite";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
return {
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV),
},
};
});
6. TypeScript types: declared, but not set
In TypeScript, Property 'env' does not exist on type 'ImportMeta' means the client types are missing. Add vite/client to compilerOptions.types in tsconfig.json, or add a vite-env.d.ts with a triple-slash reference to it; vite/client provides the types for import.meta.env[4].
For your own variables, augment ImportMetaEnv in src/vite-env.d.ts[1]:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
Keep import statements out of that file, or the augmentation stops working[1]. And remember what a type is: readonly VITE_API_URL: string tells the compiler the variable exists. It does not set it. A variable that is typed but not present at build time is still undefined in the browser, with no type error.
7. The value arrives, but not as you wrote it
- It is a string.
VITE_SOME_KEY=123arrives as"123", and booleans arrive as strings too[1], soVITE_FEATURE=falseis the truthy text"false". Convert it:import.meta.env.VITE_FEATURE === "true". - A
$is cut off. Vite expands variables in.envfiles, so a$inside a value has to be escaped with\[1]:KEY=test$foobecomestest,KEY=test\$foostaystest$foo. - In
index.html,%VITE_API_URL%is replaced likeimport.meta.env, but a variable that does not exist is left as the literal text instead ofundefined[1].
How to confirm the fix before you deploy
Build with the same command and the same variables as the server, then look for the value in the output:
VITE_API_URL=https://api.example.com npm run build
grep -rl "https://api.example.com" dist/assets/ | head
A file name means the value is baked in. No output means the build did not have it: go back to causes 1 to 4. Then try the same build without the variable on the command line, the way a fresh clone would see it: if the value disappears, it was coming from your shell or from a file that is not committed.
On Livops
- Variables are read at build time. Livops’s docs say a static site reads variables at build time (
VITE_*,NEXT_PUBLIC_*, etc.) and that they are baked into the files, visible to anyone in a browser. AddVITE_API_URLin the service’s Variables and deploy again: new values take effect on the next deploy. - No .env from your machine. An
.envfile does not reach the repository; the docs say the values go in Variables instead. That is cause 3, and the fix is the same. - Never a secret. The docs are direct: never give a static site a secret key or a database password.
- Staging and production. When a staging release of a static site is promoted, Livops rebuilds it from the same commit with production’s variables, because the values are baked in. Set
VITE_API_URLin both environments, each with its own address. - Vite is detected. Livops detects Vite and fills in the install and build commands; change them in Settings → Build or with
buildinlivops.json, which is applied on every deploy. Everygit pushto the connected branch starts a new deploy, and with it a new build. - Not
localhost. An API address that sayslocalhostpoints at the visitor’s own computer once the site is deployed; see The frontend calls localhost.
If the variable is set but the browser blocks the request, see Mixed Content for an http:// address and No ‘Access-Control-Allow-Origin’ header for a CORS error. A Vite site that answers 404 when you refresh a page: 404 on page refresh.
Questions
Why is my VITE_ variable defined locally but undefined after deploy?
Locally Vite reads your .env.local or .env.development file. The build server has neither: .env.local is ignored by git, and .env.development is only loaded in development mode, while vite build runs in production mode. Set the variable where the build runs and build again.
I changed the variable on the server. Why does the site still use the old value?
Because the value is already written into the built JavaScript. Vite replaces import.meta.env values at build time, so changing a variable on a running site changes nothing. Build the site again after every change.
Can I read a Vite env variable at runtime instead of build time?
Not through import.meta.env, which is filled in when the site is built. If one build must serve several addresses, load the value at runtime yourself, for example from a JSON file or an API on the same site, or build once per environment.
Can I use REACT_APP_ variables after moving from Create React App?
Yes, if you tell Vite about the prefix: envPrefix accepts a list, such as VITE_ and REACT_APP_. You still have to read them from import.meta.env rather than process.env. Never set envPrefix to an empty string; Vite refuses it because it would expose every variable.
Why is VITE_FEATURE=false still true in my code?
Every Vite env variable is a string, so false arrives as the text false, which is truthy. Compare it as a string, for example import.meta.env.VITE_FEATURE === 'true'.
Is it safe to put an API key in a VITE_ variable?
No. VITE_ variables are bundled into the code that every visitor downloads. Keep secrets on a server and let the site call that server.
Sources
- Vite — Env Variables and Modes (vite.dev). Checked .
- Vite — Shared Options (envPrefix, envDir, define) (vite.dev). Checked .
- Vite — Configuring Vite (Using Environment Variables in Config) (vite.dev). Checked .
- Vite — Features (Client Types) (vite.dev). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Vite siteRelated
- Mixed Content: the page was loaded over HTTPS, but requested an insecure resource — fix after deployMixed Content: The page at 'https://…' was loaded over HTTPS, but requested an insecure resource 'http://…'. This request has been blocked means your HTTPS page asked for a script, stylesheet or API call over plain http://, and the browser refused. After a deploy the usual reasons are an API address with http:// baked into the frontend build, or a backend behind an HTTPS proxy that builds its URLs with http://. Use https:// or relative URLs, rebuild, and make the backend trust its proxy.
- 404 on page refresh in a React or Vue app (SPA): how to fix itA 404 when you refresh a page or open a link like /about in a React Router or Vue Router app means the static host looked for a file at /about, found none, and never loaded index.html, where the router lives. Fix it on the host by rewriting every route to /index.html (Netlify _redirects, Vercel rewrites, nginx try_files), or switch to hash routing. The price of a rewrite: unknown paths stop being 404s unless the app shows its own.
- Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource — the fixBlocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource means the browser read the API's response, or its answer to the OPTIONS preflight, and found no permission for your site's origin. After a deploy the usual reason is that the frontend and the API now live at different addresses. Allow the exact frontend origin on the server, answer OPTIONS, keep the headers on error responses, or serve the frontend and the API from one origin.
- Module not found: Can't resolve './components/Header' in webpack and Next.js: how to fix itModule not found: Can't resolve './components/Header' means the bundler followed an import and found no file or package there. The usual causes: the file name's case differs from the import (fine on macOS and Windows, fatal on a Linux build server), a wrong relative path or a missing extension, a package that is not in package.json, an @/ alias the bundler does not know, and, for Can't resolve 'fs', Node-only code pulled into the browser bundle.
- Free static site hosting in 2026: the free tiers comparedA static site — plain HTML, or a Vite, React or Astro build, or a Lovable export — is free on all five. The differences are the limits: Netlify pauses every site when 300 monthly credits run out, Vercel Hobby is for non-commercial use only, GitHub Pages is not for running a business, and Cloudflare Pages does not count static traffic. On Livops up to 30 sites are free, on your own domain, with no card asked for.
- A staging environment next to productionOn Livops, Add environment on the project page makes a staging copy of your production services, each with its own address, its own variables and its own empty database, so a test never touches production data. Promote to production then ships the exact release you tested, without rebuilding. A staging environment costs half; pull request previews are billed like regular services.