Vite works locally but fails after deploy: fix the API URL
Your AI coding agent ran npm run dev and the app worked. You deploy it, the page loads, and every API request fails. Open DevTools → Network, reload the deployed page, and click the first failed API request. The request URL and the response headers usually tell you whether to fix the Vite build, the host's routing, or the API.
Start with the request your browser actually made
| What you see on the deployed page | What to check first |
|---|---|
Request URL contains localhost, 127.0.0.1, or your old staging domain |
Find the value in the deployed JavaScript and check the environment used to build it. |
/api/... returns 200 with Content-Type: text/html |
Inspect the body. If it starts with <!doctype html, a frontend fallback or sign-in page probably answered. |
/api/... returns 404 |
Check the route at the API upstream and at the frontend host. Compare where the /api prefix appears. |
| The right API URL appears, but the console reports CORS | Inspect the browser's Origin, the response's allowed origin, and any failed OPTIONS preflight. |
If no API request appears, look for an earlier JavaScript error or a failed JS asset. A Vite app deployed under a path like /demo/ may need a matching base for its built assets. Vite's guide to the public base path.
Fix Vite env variables that work locally but fail in production
Search the source for VITE_API_URL and any fallback next to it. This example sends requests to localhost whenever the build omits the variable.
const apiOrigin = import.meta.env.VITE_API_URL || 'http://localhost:8787'
fetch(new URL('/api/health', apiOrigin))
In a visitor's browser, localhost refers to that visitor's computer. Set VITE_API_URL in the environment that runs the frontend build, then rebuild and deploy the resulting files. Editing an environment variable on the server after it starts serving an existing dist/ leaves those files as they were. Vite substitutes import.meta.env.VITE_API_URL during the build. Vite env variables and modes.
Check the mode and the source of the value. vite build uses production by default. vite build --mode staging loads .env.staging. A value already in the build process environment takes precedence over values in the files. In a local fixture with a public staging URL in .env.production, setting VITE_API_URL=http://localhost:8787 on the build process still put localhost in the resulting JavaScript.
You can also check what the build produced. Run this ripgrep (rg) command from the project root to search dist/assets.
rg --only-matching --no-line-number 'localhost:8787|staging-api\.example' dist/assets
Substitute the specific URL or hostname from Network. A match can come from code your app never runs. The deployed request URL is the stronger evidence. If it disagrees with your fresh build, check the deploy's artifact, the HTML's asset hash, and any cache or service worker before trying more env changes.
VITE_ variables are public in a client bundle. An API origin belongs there if you need it. Keep database passwords and provider API keys in the backend, where the backend can use them on behalf of the user.
Give /api a route on the production host
If the app and API can share the public origin, use a root-relative path such as /api/health in the frontend.
fetch('/api/health', { headers: { Accept: 'application/json' } })
That sends the request to the host that served the page. During development, Vite can forward the path to a local API. Merge the proxy rule below into your Vite config with the port your API uses.
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
proxy: {
'/api/': 'http://127.0.0.1:8787',
},
},
})
This rule preserves /api/health when forwarding it. If your backend has /health, configure the rewrite explicitly and check the forwarded path on both hosts. vite preview inherits server.proxy by default, so even a successful preview can hide the missing route in production. Vite preview proxy settings.
Configure the production host to send /api/* to your backend or serverless function before applying a single-page app fallback. Let unknown API routes return an API 404. Use the fallback for browser navigation paths, so reloading /settings can still load index.html. Vercel's rewrite examples.
We sent the same GET /api/health request with Accept: application/json to four local servers. The fixture ran on Vite 8.3.2 and Node 22.14.0.
| Server receiving the request | Status | Response |
|---|---|---|
vite dev with server.proxy |
200 | application/json, {"status":"ok"} |
vite preview with the inherited proxy |
200 | application/json, {"status":"ok"} |
| Simulated static host with a catch-all fallback | 200 | text/html, the built index.html |
Simulated host with the /api/ route before the fallback |
200 | application/json, {"status":"ok"} |
If you keep the API on a different origin, build the frontend with that API's public HTTPS address and configure CORS on the API for the frontend origin. A request with cookies needs the exact allowed origin and Access-Control-Allow-Credentials: true, subject to the browser's cookie rules. A successful curl or Node request only proves that the server answered. Use the browser to verify that the page can read the response. Fetch standard on credentialed CORS.
Check the deployed API's status, content type, and body
Run the check against the same public URL the frontend is supposed to call. In this example, /api/health is a public, read-only route that returns 200 and {"status":"ok"}. If you already have a health route, change the expected shape to match its contract. Keep it free of internal details.
// scripts/check-api.mjs (Node.js 22+)
const url = process.argv[2]
if (!url) throw new Error('Usage: node scripts/check-api.mjs <health-url>')
const response = await fetch(url, {
headers: { Accept: 'application/json' },
redirect: 'manual',
signal: AbortSignal.timeout(10_000),
})
const type = response.headers.get('content-type') ?? ''
if (response.status !== 200 || !/^application\/json\s*(;|$)/i.test(type)) {
throw new Error('Expected 200 JSON, got HTTP ' + response.status + ' ' + type)
}
const body = await response.json()
if (body?.status !== 'ok') throw new Error('Unexpected health response')
console.log('API health check passed')
node scripts/check-api.mjs https://your-app.example/api/health
The script failed on the simulated host that returned 200 text/html and passed after the API route was added. It also failed on a 200 JSON response with the wrong body. Run it after each staging deploy. For flows involving login, upload, or saved data, follow it with one browser test of the actual user action. A health endpoint can succeed while those routes fail. How to test AI-generated code.
Give your coding agent the request details
Replace the bracketed values with the evidence you have. Omit cookies, authorization headers, and private response data.
The deployed page issues GET [request URL]. I expected HTTP 200 with
application/json and {"status":"ok"}. It returned [status and content type].
Trace the URL from the frontend source through the production build and host
routing. Check which Vite mode and public API URL the build used. Inspect the
production /api route and the SPA fallback in their applied order. Preserve
the local dev workflow. Show me the smallest patch and give me the check to
run against the deployed URL.
The useful handoff is the first failing request, plus the same check passing on the new deployment. That gives the agent a result it can reproduce without relying on npm run dev.