Dev Server Proxying and Migrating from Older Bundlers

Dev Server Proxying and Migrating from Older Bundlers in Vite: A visitor calls a company's one published phone number and asks for "somebody in accounts," and…

The Analogy: The Company Switchboard

A visitor calls a company's one published phone number and asks for "somebody in accounts," and a switchboard operator - not the visitor - knows that accounts is extension 214 and patches the call straight through, so the caller only ever deals with the single public number and never learns the private extensions humming behind it. The dev server is that one public number: your app fetches /api/users from its own origin, and server.proxy is the operator that quietly connects that request to the backend on another port, so the browser never sees a second origin and its cross-origin defenses never wake up.

The operator does small fixups while connecting a call: trimming a department name the internal team stopped using years ago before repeating the request (a rewrite that strips a path prefix the backend does not expect), announcing the call as "internal, from the front desk" so a wary extension picks up (changeOrigin, which rewrites the outgoing Host header), and, for a caller who needs a running back-and-forth rather than one clipped message, opening a dedicated line that stays live (ws: true for a websocket upgrade).

The operator works down a fixed printed list of routing rules and connects the FIRST rule that fits the request, so a broad rule near the top of the sheet quietly catches every call that would also have matched a narrower rule below it; a request that fits no rule at all is simply dealt with at the front desk itself, the way an unmatched URL falls through to the dev server and is served as one of your own app routes.

The switchboard, though, lives only in head office. When the company opens an unstaffed branch - the production build, a folder of static files with no dev server and nothing that ever reads server.proxy - the callers you trained to "dial the one number and ask for accounts" reach a dead line, because no operator is standing there to forward them; that branch has to be given its own routing, a reverse proxy or CDN rule or host config, before those very same calls connect again.


Syntax or Core Structure

server.proxy is a dev-server-only option in vite.config.js. Each key is a path context, and its value tells Vite where to forward a matching request and how to adjust it on the way.

export default defineConfig({
  server: {
    proxy: {
      // forward /api/* to the backend, unchanged
      '/api': { target: 'http://localhost:8080', changeOrigin: true },
      // strip a prefix the backend does not expect
      '/legacy': {
        target: 'http://localhost:9000',
        changeOrigin: true,
        rewrite: (p) => p.replace(/^\/legacy/, ''),
      },
      // websockets need an explicit opt-in
      '/socket': { target: 'ws://localhost:8080', ws: true },
    },
  },
})

A string key matches when the request URL starts with it; a key beginning with ^ is treated as a regular expression instead. Vite checks the contexts in the order you wrote them and forwards to the first one that matches. Anything that matches no context is left alone for the dev server to serve as an app route. The same routing table, exercised against a handful of URLs, makes the behaviour concrete:

function matchContext(ctx, url) {
  return ctx.startsWith('^') ? new RegExp(ctx).test(url) : url.startsWith(ctx);
}
function route(proxy, url) {
  for (const ctx of Object.keys(proxy)) {
    if (!matchContext(ctx, url)) continue;
    const rule = proxy[ctx];
    if (rule.ws) return 'proxy ' + rule.target + url + ' (websocket)';
    if (rule.rewrite) return 'proxy ' + rule.target + rule.rewrite(url) + ' (rewrite)';
    return 'proxy ' + rule.target + url + (rule.changeOrigin ? ' (changeOrigin)' : '');
  }
  return 'app route (dev server handles it)';
}

Output:

/api/users       -> proxy http://localhost:8080/api/users (changeOrigin)
/legacy/users/7  -> proxy http://localhost:9000/users/7 (rewrite)
/socket          -> proxy ws://localhost:8080/socket (websocket)
/home            -> app route (dev server handles it)

/api/users and /socket reach their backends untouched, /legacy/users/7 arrives at port 9000 with the /legacy prefix already stripped, and /home matches nothing, so the dev server renders your app for it. The browser issued four same-origin requests; the operator decided where each one actually went.


Technical Depth: How the Dev Server Routes and What Migration Changes

The proxy options and how a URL is matched

Each context value is a small options object. The ones you reach for most:

OptionWhat it does
targetThe origin to forward matching requests to
changeOriginRewrite the Host header to the target's host
rewriteTransform the path before forwarding

| ws | Proxy websocket (upgrade) connections too | | secure | Set false to accept a self-signed TLS cert in dev | | configure | Reach the underlying http-proxy for custom events |

Matching is a plain first-fit scan: Vite walks the contexts in declaration order and stops at the first whose key the URL starts with (or whose ^-anchored regex matches). It does not pick the longest or most specific match - only the first - which is why the order you write the rules in is part of their meaning, not just cosmetics.

Rewriting the path safely

A rewrite is an ordinary function from the incoming path to the forwarded path. The usual job is stripping a prefix, and the regex must be anchored with ^ so it only touches a leading segment:

const rewrite = (p) => p.replace(/^\/legacy/, '');        // strips a leading /legacy
const safe    = (p) => p.replace(/^\/legacy/, '') || '/'; // never returns an empty path

Output:

rewrite: (p) => p.replace(/^\/legacy/, "")
  /legacy/users  -> "/users"
  /legacy/       -> "/"
  /legacy        -> ""
  /api/legacy    -> "/api/legacy"
safe: append || "/" so an exact match keeps a leading slash
  /legacy        -> "/"

Two edges earn the anchor and the fallback. /api/legacy is left untouched because the prefix is not at the start, and a bare /legacy rewrites to the empty string, which most backends treat as a malformed path - the || '/' guard turns it back into a root request. A rewrite without the ^ anchor would happily strip /legacy from the middle of any path, corrupting URLs it was never meant to touch.

changeOrigin, websockets, and regex contexts

By default the proxied request keeps the browser's original Host header, which points at your dev server. changeOrigin: true rewrites it to the target's host, and many backends need that - virtual-hosted services route on Host, and anything that issues redirects will otherwise send the browser back to the dev origin. Websocket connections are a separate opt-in: a normal proxy rule ignores the HTTP upgrade handshake, so a live socket needs ws: true on its context. When a plain prefix is too blunt - you want /api but not /api-docs - switch to a regex context such as ^/api/ (note the trailing slash), which matches exactly what you intend instead of every path that merely starts with those characters.

Migrating from an older bundler

Moving a project from webpack, CRA, or Parcel is mostly deletion. Most loader and plugin configuration simply disappears because Vite handles it natively, and the concepts that remain map across cleanly:

Old conceptVite equivalent
resolve.aliasresolve.alias (use absolute paths)
Loader rulesBuilt in, or a single plugin
devServer.proxyserver.proxy
publicPathbase
output.pathbuild.outDir
DefinePlugindefine, or import.meta.env
process.env.FOO (client)import.meta.env.VITE_FOO
require.contextimport.meta.glob

The environment-variable line is the one that bites, because it is not a pure rename. Client code that read process.env.FOO must read import.meta.env.VITE_FOO, and the variable is only exposed if it carries the VITE_ prefix in .env. That prefix is a deliberate gate, so migration is the moment to sort every variable into "safe to ship to the browser" or "must move server-side":

Output:

process.env.API_URL          -> import.meta.env.VITE_API_URL (add VITE_ prefix in .env)
process.env.NODE_ENV         -> import.meta.env.MODE (built in)
process.env.STRIPE_SECRET    -> SERVER-SIDE ONLY (secret: do not ship to client)
require('./util')            -> ESM import (add explicit .js extension)
require.context('./icons')   -> import.meta.glob (glob import)

API_URL becomes a prefixed client variable, NODE_ENV is already covered by the built-in import.meta.env.MODE, and STRIPE_SECRET is flagged rather than renamed - blindly prefixing a secret with VITE_ is how a private key ends up in a public bundle. The two require forms become ESM: a plain require is a static import with an explicit extension, and require.context becomes import.meta.glob.


Real World Example: A Proxy Table Whose Order Hides a Route

A team runs two backends in development: a general API on one port and a metrics service on another. They add both to the proxy table, list the general rule first because it is the one they type most, and everything appears to work - both endpoints return data, the dashboard renders, the build ships.

function route(proxy, url) {
  for (const ctx of Object.keys(proxy)) {
    if (url.startsWith(ctx)) return { target: proxy[ctx], rule: ctx };
  }
  return null;
}

function deadRules(proxy) {
  const keys = Object.keys(proxy);
  const dead = [];
  for (let i = 0; i < keys.length; i++) {
    for (let j = 0; j < i; j++) {
      if (keys[i].startsWith(keys[j])) { dead.push(keys[i]); break; }
    }
  }
  return dead;
}

function report(label, proxy) {
  console.log(label);
  for (const url of ['/api/users', '/api/internal/cpu']) {
    const r = route(proxy, url);
    const want = url.startsWith('/api/internal') ? 'metrics' : 'api';
    const got = r.target.includes('metrics') ? 'metrics' : 'api';
    const flag = got === want ? '' : '   << WRONG: wanted ' + want;
    console.log('  ' + url.padEnd(18) + ' -> ' + r.target.padEnd(22) + '(rule ' + r.rule + ')' + flag);
  }
  const dead = deadRules(proxy);
  console.log('  dead rules: ' + (dead.length ? dead.join(', ') : '(none)'));
}

const buggy = { '/api': 'http://api:8080', '/api/internal': 'http://metrics:9090' };
const fixed = { '/api/internal': 'http://metrics:9090', '/api': 'http://api:8080' };

report('BUGGY ORDER (broad rule first):', buggy);
console.log('');
report('FIXED ORDER (specific rule first):', fixed);

Output:

BUGGY ORDER (broad rule first):
  /api/users         -> http://api:8080       (rule /api)
  /api/internal/cpu  -> http://api:8080       (rule /api)   << WRONG: wanted metrics
  dead rules: /api/internal

FIXED ORDER (specific rule first):
  /api/users         -> http://api:8080       (rule /api)
  /api/internal/cpu  -> http://metrics:9090   (rule /api/internal)
  dead rules: (none)

With the broad /api rule listed first, every request starting with /api - including /api/internal/cpu - matches it and is forwarded to the general API. The /api/internal rule sits right below it and can never win, because any URL that would match it has already matched /api one line earlier. It is dead code that looks like configuration.

The bug hides in exactly the conditions that should catch it. In development both backends are up, so the metrics request gets a 200 and a JSON body; it is simply the WRONG body, served by the general API instead of the metrics service. Nothing errors, nothing 404s, and a quick click-through of the dashboard looks healthy - the numbers are just quietly coming from the wrong place.

The flaw is not a typo and not either target being wrong; both targets are correct. The defect is that the proxy table's meaning depends on declaration order, and a broad prefix was placed above a more specific one. First-fit matching means specificity has to be expressed by hand, as position - the exact thing an alphabetised or "most-used-first" ordering destroys.

The durable fix is to order proxy rules most-specific-first, so narrower prefixes get their chance before broader ones, or to use ^-anchored regex contexts that match a rule exactly rather than by prefix. Either way the table should be read like a routing table, where specificity sets the order and no rule is allowed to shadow another.


Common Mistakes

  1. Hardcoding the dev backend in fetch. Calling http://localhost:8080/api directly bypasses the proxy and breaks in production; fetch a relative /api path so the same code is proxied in dev and same-origin in prod.
  1. Expecting server.proxy to exist in production. The proxy is a dev-server feature; vite build emits static files with no server, so production routing must be set up separately in your reverse proxy, CDN, or host.
  1. Ordering proxy rules broad-first. First-fit matching means a general prefix listed above a specific one shadows it; put the most specific contexts first, or use anchored regex contexts.
  1. Forgetting changeOrigin for host-routed backends. Without it the proxied request keeps the dev server's Host, so virtual-hosted targets and redirect-issuing backends misbehave.
  1. Writing a rewrite regex without the ^ anchor. An unanchored replace strips the prefix wherever it appears, mangling paths like /api/legacy; anchor it so only the leading segment is removed.
  1. Proxying websockets without ws: true. A plain rule ignores the upgrade handshake, so the socket silently fails to connect; opt in explicitly on that context.
  1. Prefixing a secret with VITE_ during migration. It makes the value available, and ships it to every browser; secrets must move server-side, not gain a client prefix.
  1. Porting the old bundler config line by line. Most loader and plugin setup is built into Vite; start from an empty config and add only what actually breaks.
  1. Trusting the dev server as proof the migration is done. The dev server comes up early and looks like success; case-sensitive paths and interop issues only surface under vite build and vite preview.

Best Practices

  • Fetch relative paths. Request /api/... rather than an absolute origin so one code path works proxied in development and same-origin in production.
  • Order contexts most-specific-first. Treat the proxy table as a routing table where position encodes specificity, so no broad rule can shadow a narrower one.
  • Anchor every rewrite. Start prefix-stripping regexes with ^ and guard the empty result with || '/' so an exact-prefix request stays a valid path.
  • Set changeOrigin deliberately. Turn it on for host-routed or redirecting backends, and know why when you leave it off; it is the field people forget when redirects go astray.
  • Plan the production equivalent up front. Decide where /api routing lives once deployed - reverse proxy, CDN rule, or host config - before you rely on the dev proxy.
  • Migrate by subtraction. Delete old loader and plugin config and start from an empty Vite config, adding back only what a real failure demands.
  • Audit env vars during the move. Sort each process.env use into a VITE_-prefixed client variable or a server-side secret; migration is the natural checkpoint.
  • Verify the build, not just vite. Run vite build and vite preview and click every route, because case sensitivity and interop problems appear only there.

Practice Exercises

  1. Route by hand. Given contexts ['/api', '/api/v2', '/assets'] in that order and the URL /api/v2/users, state which rule Vite forwards to and why, then reorder the table so /api/v2 can actually be reached.
  1. Fix the rewrite. A rewrite of (p) => p.replace(/legacy/, '') is corrupting the path /services/legacy-report. Explain what it does to that path and rewrite it so only a leading /legacy segment is stripped.
  1. Trace the 404. After migrating, local development works but the deployed app's /api calls 404. The old config had a devServer.proxy entry. Explain what was missed and where the equivalent routing belongs in production.
  1. Translate the env vars. You inherit client code using process.env.API_BASE and process.env.SESSION_SECRET. Give the correct Vite treatment for each, and explain why one of them must not simply be renamed with a VITE_ prefix.