skip to content

In Vite's dev server, how do you configure server.proxy so /api calls and a websocket feed reach a backend on port 8080?

level: middleimportance: should knowfreq 16%

answer

  1. same origin from the browser's view
  2. path-prefix keys, caret for a regex
  3. target, changeOrigin, rewrite
  4. ws true for socket upgrades
  5. dev and preview only, never the build

basics

~20 s

Add server.proxy entries keyed by path prefix: '/api' with target http://localhost:8080, changeOrigin and a rewrite that strips the prefix, and '/feed' with a ws:// target and ws: true. The browser stays same-origin, so no CORS.

solid answer

~40 s

`server.proxy` maps keys to proxy options; any request whose path starts with a key is forwarded to its `target` (a key starting with `^` is a regular expression). For the API, `'/api': { target: 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') }`: `changeOrigin` sets the forwarded request's Host header to the target's and `rewrite` removes the prefix the backend does not know. For the feed, `'/feed': { target: 'ws://localhost:8080', ws: true }` forwards the WebSocket upgrade. The browser only ever talks to the dev server's origin, so no CORS headers are needed, and proxied requests are not transformed by Vite. It exists only in development and in `vite preview`, where `preview.proxy` defaults to it; the deployed app needs a real reverse proxy or a same-origin backend.

code

typescript · 20 lines
typescript
// vite.config.ts
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      // http://localhost:5173/api/routes -> http://localhost:8080/routes
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      // ws://localhost:5173/feed -> ws://localhost:8080/feed
      '/feed': {
        target: 'ws://localhost:8080',
        ws: true,
      },
    },
  },
})

go deeper

for a junior

Recall that the app calls its own origin and the dev server forwards matching paths to the backend, which is why no CORS setup is needed in development.

for a middle

Explain each rule option: target, changeOrigin, rewrite for prefix stripping, ws for upgrades, and that a matched request bypasses Vite's transforms.

for a senior

Show the operational edges: targets are resolved from the dev server's network, preview reuses the rules, the build has none, and proxied sockets leave Origin checks to the backend.

for a principal

Decide whether teams should mirror production routing in development through the proxy or run a shared local gateway, trading setup cost against drift between dev and deployed request paths.

## Why a dev proxy at all During development the dispatch console is served by Vite's dev server on one origin, say `http://localhost:5173`, while its API listens on `http://localhost:8080`. A call from the page straight to port 8080 is a **cross-origin request**, so the backend would have to send CORS headers that production never needs. `server.proxy` removes the problem: the page calls **its own origin** (`/api/routes`), and the dev server forwards the request to the backend and streams the answer back. To the browser, everything is same-origin. ## How a rule matches `server.proxy` is an object of `{ key: options }` pairs: - A request whose **path starts with the key** is proxied to that rule's target. - A key that starts with `^` is read as a **regular expression**, for example `'^/fallback/.*'`. - A string value is shorthand for `{ target: value }`. - If the app uses a non-relative `base`, each key must start with that base. - A request that matches a rule is **not transformed by Vite**; it goes to the backend untouched. That last point is why keys should be specific. A key as broad as `/` would match Vite's own module requests too and send them to the backend. ## The options that matter | Option | What it does | When you need it | |---|---|---| | `target` | where matching requests go (`http://…`, or `ws://…` for sockets) | always | | `changeOrigin` | sets the forwarded request's Host header to the target's host | backends or virtual hosts that check Host | | `rewrite` | a function from the incoming path to the forwarded path | the backend has no `/api` prefix | | `ws` | also forwards WebSocket upgrade requests | the live feed | | `configure` | gives you the underlying proxy instance | custom logging or headers | `rewrite` changes the **path only**. With `rewrite: (path) => path.replace(/^\/api/, '')`, `/api/routes?depot=4` reaches the backend as `/routes?depot=4`. ## The websocket feed The console's live vehicle positions arrive over a WebSocket. A rule such as `'/feed': { target: 'ws://localhost:8080', ws: true }` forwards the upgrade, so `new WebSocket('ws://localhost:5173/feed')` in the page reaches the backend's `/feed`. Two cautions from Vite's documentation: 1. Vite **does not check the Origin header** of WebSocket requests before proxying; the backend is expected to. 2. `rewriteWsOrigin: true` rewrites that header to the target's origin, which **bypasses** the backend's origin check and can leave it open to CSRF, so use it only when you understand the trade. This proxied socket is unrelated to Vite's own HMR connection, which the dev server manages separately; it needs no proxy rule of its own. ## Where the target is resolved The proxy runs **inside the dev server process**, so `target` is resolved from where Vite runs, not from the browser. In a dev container, `localhost:8080` means the container's own port 8080; if the API runs in a neighbouring container, the target is that container's hostname, such as `http://api:8080`. ## What the proxy is not - It is **not part of the build**. `vite build` emits static files with no proxy in them. - `vite preview` has `preview.proxy`, which **defaults to `server.proxy`**, so a local preview behaves like dev. - The deployed console must reach `/api` some other way: the same origin as the backend, or a reverse proxy in front of both. - In `server.middlewareMode`, a WebSocket proxy needs the parent HTTP server passed as `middlewareMode: { server }` so upgrades can be bound. ## Debugging a rule that seems skipped - In the browser's network panel the request always shows the **dev server's origin**; that is the proxy working, not a sign it was bypassed. - Check that the path really **starts with the key**, including any `base` prefix. - Use `configure` to attach listeners to the underlying proxy instance, for example to log each forwarded path, when you need to see what reached the backend. - Remember the `rewrite` result is what the backend sees; log it before blaming the backend's routes. ## Checklist 1. Call relative paths (`/api/...`, `/feed`) from the app, never `http://localhost:8080`. 2. One rule per prefix, as narrow as the backend's routes allow. 3. `changeOrigin` when the backend cares about Host; `rewrite` when it has no prefix. 4. `ws: true` on the socket rule, and let the backend check Origin. 5. Plan the production path separately; the dev proxy does not ship.

  • The proxy works in development, but the deployed console's /api calls return the static host's 404 page; why?
    Because `server.proxy` belongs to the dev server, and `vite preview` reuses it through `preview.proxy`; `vite build` emits only static files. In production something else must route `/api`: serving the app from the backend's origin, or a reverse proxy in front of both. The relative URLs in the app are right; the routing has to be provided by the deployment.
  • Inside a dev container, the /api rule targets localhost:8080 and every call fails, although the API container is running; what is wrong?
    The proxy runs in the dev server process, so `localhost` means the dev container itself, where nothing listens on 8080. The target must be an address the dev server can reach, such as the API container's hostname (`http://api:8080`), not the address the browser would use.

  • changeOrigin adds CORS headers to the backend's responses
  • rewrite edits the response body before it reaches the browser
  • server.proxy rules are compiled into the production bundle
  • A proxy rule is needed for Vite's HMR socket to connect
  • Vite checks the Origin header on proxied WebSocket requests