Vite Proxy Not Working: Read the Response First

When the Vite proxy is not working, the response tells you which part failed. index.html with a 200 means no server.proxy rule matched the request. A 404 from your API means a rule matched and forwarded the wrong path. An empty 502 means Vite could not connect to the target. A CORS error means the browser never used the proxy.

We ran each case below on Vite 8.4.0 and Node 24.12.0 against a small local API on port 4567, with headless Chromium 149 for the browser errors. Take the app out of the picture first. Ask the dev server directly and read the status line and the Content-Type:

curl -i http://localhost:5173/api/users

Why does fetch return index.html instead of JSON?

No proxy key matched, so Vite’s single-page-app fallback answered. A GET whose Accept header allows */*, which is what fetch() sends unless you set one, gets index.html and a 200. Calling .json() on that page threw this in Chromium:

SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON

A POST to the same unmatched path, or a GET that accepts only application/json, got an empty 404 from Vite with no Content-Type. If your API’s 404 has a body, the two are easy to tell apart.

The server.proxy docs give the matching rule in two sentences: “Any requests whose request path starts with that key will be proxied to the specified target. If the key starts with ^, it will be interpreted as a RegExp.” Three mistakes break it. A key written as api, with no leading slash, never matches, because every request path begins with /. A proxy object at the top level of the config, instead of under server, is ignored. And a request that carries your base, such as /app/api/users, does not match a /api key. None of the three logged a warning.

To see what did match, start Vite with proxy debugging on:

npx vite --debug proxy

Each proxied request prints a line like vite:proxy /api/users -> http://localhost:4567. If there is no line, no rule matched.

“Starts with” also means a plain key matches more than you intended. /api took a request for /apiary, and with the rewrite from the docs example our API received it as /ary. Write the key as ^/api/ instead. Rules are tried in the order you wrote them and the first match wins, so a general /api placed above /api/users took every request.

Why does the API return 404 through the proxy?

The object form forwards the path as it came in: /api/users reaches the API as /api/users. If the API serves /users, strip the prefix with rewrite. A path on the target is added in front, so a target of http://localhost:4567/v1 turned the rewritten /users into /v1/users.

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      '^/api/': {
        target: 'http://localhost:4567',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
})

The string shorthand, '/api': 'http://localhost:4567', also sets changeOrigin: true for you. The object form leaves it off, which is the default in http-proxy-3, the library Vite has used for proxying since 7.1. With it off our API saw Host: localhost:5173. With it on, it saw Host: localhost:4567. Any target that routes by hostname, as a virtual host or a CDN does, needs it on.

What does a 502 from the Vite dev server mean?

Vite reached for the target and got no response. Since Vite 8.0 the proxy answers that with 502 Bad Gateway and an empty body, where earlier versions sent a 500, a change listed in the changelog and one of many in that release (our Vite 8 migration notes cover the build side). The reason goes to the terminal, shown here without its timestamp and stack:

[vite] http proxy error: /users
AggregateError [ECONNREFUSED]:

The path in that log is the rewritten one, /users and not /api/users. The AggregateError with an empty message is what a localhost target produces when nothing is listening: since Node 20, a connection tries the IPv6 and IPv4 addresses in turn and reports the failures together, as the net docs describe under autoSelectFamily. A target of http://127.0.0.1:4567 gave the readable version, Error: connect ECONNREFUSED 127.0.0.1:4567. Both mean the same thing. Start the API, or correct the port.

Trying both addresses also makes an old fix unnecessary. Swapping localhost for 127.0.0.1 used to help when only the first resolved address was tried. On Node 24 a localhost target reached our API even though it was bound to 127.0.0.1 alone.

An HTTPS target with a self-signed certificate also returns 502, and the log line begins Error: self-signed certificate. secure: false turns certificate checking off for that rule. Keep it to local targets.

Why is there still a CORS error?

The request did not go through the proxy. A proxied call is same-origin to the browser, since the page and the request both use http://localhost:5173, so CORS is never consulted. When Chromium prints this, read the first URL:

Access to fetch at 'http://127.0.0.1:4567/users' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

That is the API’s own address, so the code called it directly. Look for an absolute base URL in an environment variable or an axios baseURL, and make the call relative: fetch('/api/users'). Changing server.cors will not help, because it sets the headers the dev server sends and the blocked response came from the API.

Why do logins and cookies fail through the proxy?

Check two headers first. changeOrigin rewrites Host and nothing else. On a POST the browser’s Origin header still read http://localhost:5173 when it reached our API, and a backend that compares Origin with its own host as a CSRF check, the kind of filter our Sec-Fetch-Site post describes, will refuse it. The headers option overrides it.

The second is Set-Cookie. Our API set a cookie with Domain=api.example.test, the proxy passed it through unchanged, and Chromium discarded it because the page was on localhost. cookieDomainRewrite: '' removes the attribute, so the cookie belongs to whichever host served the response.

// vite.config.js
import { defineConfig } from 'vite'

const target = 'https://localhost:8443'

export default defineConfig({
  server: {
    proxy: {
      '^/api/': {
        target,
        changeOrigin: true,
        secure: false, // self-signed certificate on a local API only
        ws: true,
        headers: { origin: target },
        cookieDomainRewrite: '',
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
})

With that config the login cookie was stored for localhost and sent on the next proxied request. ws: true is there because WebSocket upgrades are only proxied when it is set, or when the target starts with ws:. Without it our socket was still in CONNECTING three seconds later, with no error event. A redirect back to the API’s own host is passed through as well; autoRewrite: true pointed the Location header at the dev server, and an HTTPS target needed protocolRewrite: 'http' on top.

Why is the Vite proxy not working in production?

It does not exist there. server.proxy belongs to the dev server. vite build writes static files, and our dist held nothing that could forward a request. vite preview does proxy, because preview.proxy defaults to server.proxy, and that makes a working preview poor evidence that production will work. Whatever serves the built site has to forward /api itself: an nginx location block, a rewrite rule on the host, or a Worker in front. If that host has its own single-page-app fallback, the first sign of a missing rule is the same HTML-where-JSON-should-be error from the top of this post.

What we would do

Keep every API call relative. Write the key as ^/api/, set changeOrigin: true, and decide once whether the API wants the prefix. When something breaks, curl the dev server before reading any application code, because the status and the content type name the failing part. Add the matching rule to the production host at the same time as the dev one, so nobody reaches for absolute URLs and CORS headers on deploy day.

We would not use the dev proxy to hide a third-party API key. It does not exist in production, so the key needs a real server-side route anyway, and that route can serve development too.

We build React and TypeScript front ends against separate APIs, and set up the dev proxy and the production routing as a pair. If yours behave differently from each other, our React development work covers that kind of fix.

Need this built properly?

Get in touch

Hack the planet!