Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Dev Server and HMR

Proxy, CORS and HTTPS in Development

Configure server.proxy to forward API calls to a backend, avoid CORS errors in development, rewrite paths, proxy WebSockets, and serve the Vite dev server over HTTPS.

A front-end app usually talks to a backend: a Laravel, Express, Django or Spring API. In development the front end runs on http://localhost:5173 and the API on http://localhost:8000. Those are different origins, so the browser applies CORS rules and may block the response. Vite's built-in proxy solves this cleanly, and the same server section handles HTTPS for features that require a secure context. This lesson covers both.

Vite is not installed on this site, so the config blocks are read-only. The runnable examples model the proxy rule matching and path rewriting, which is where mistakes usually happen.

Why CORS appears

The browser compares origins: scheme, host and port. A page at http://localhost:5173 calling http://localhost:8000/api/users is cross-origin. The API must reply with Access-Control-Allow-Origin, and for requests with custom headers or JSON bodies the browser first sends a preflight OPTIONS request. If the server does not answer correctly, you see:

TEXT
Access to fetch at 'http://localhost:8000/api/users' from origin
'http://localhost:5173' has been blocked by CORS policy

You can fix it on the server by sending the right headers, but in development there is a simpler way: make the request same-origin by letting Vite forward it.

server.proxy

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

export default defineConfig({
  server: {
    proxy: {
      '/api': 'http://localhost:8000',
    },
  },
});

Now the browser calls fetch('/api/users') on the Vite origin. Vite forwards it to http://localhost:8000/api/users and returns the response. The browser only ever sees localhost:5173, so there is no CORS check at all. In production you would typically use a reverse proxy (nginx, Cloudflare, your platform's rewrites) doing the same job.

Keys are path prefixes. A key that starts with ^ is a regular expression.

Options form

JavaScript
server: {
  proxy: {
    '/api': {
      target: 'http://localhost:8000',
      changeOrigin: true,
      secure: false,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
    '/socket.io': {
      target: 'ws://localhost:3001',
      ws: true,
    },
    '^/fallback/.*': {
      target: 'http://localhost:9000',
      rewrite: (path) => path.replace(/^\/fallback/, ''),
    },
  },
}
Option Meaning
target Where to forward requests (http://, https:// or ws://)
changeOrigin Rewrite the Host header to the target. Needed for virtual hosts and many hosted APIs
secure Set false to accept self-signed HTTPS certificates on the target
rewrite Function that changes the path before forwarding
ws Also proxy WebSocket upgrades on this path
configure Access the underlying http-proxy instance to add event handlers and logging
headers Extra request headers to send to the target

Rewriting paths

Many teams use /api in the front end while the backend routes have no /api prefix. rewrite removes it:

TEXT
browser:  GET /api/users       Vite forwards: GET http://localhost:8000/users

Check the rule with a runnable model. It follows the matching rules (prefix or regex, first match wins, then rewrite).

Node.js Stand-in: which proxy rule matches?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the last line: /apikey also matches the prefix /api, a classic surprise. Use '/api/' with a trailing slash, or a regex such as '^/api(/|$)', to avoid proxying paths you did not mean to.

Logging and debugging a proxy

Use configure to print what happens:

JavaScript
'/api': {
  target: 'http://localhost:8000',
  configure: (proxy) => {
    proxy.on('error', (err) => console.log('proxy error', err.message));
    proxy.on('proxyReq', (proxyReq, req) => console.log('->', req.method, req.url));
    proxy.on('proxyRes', (proxyRes, req) => console.log('<-', proxyRes.statusCode, req.url));
  },
},

If you see ECONNREFUSED, the backend is not running or the port is wrong. If cookies fail to stick, see cookieDomainRewrite and cookiePathRewrite options of the proxy, or use changeOrigin: true.

Server-side CORS settings

server.cors controls the CORS headers on Vite's own responses (not the proxied API). In recent versions it is limited to localhost origins by default. To allow a specific other site (for example a page on another dev domain loading modules from your dev server):

JavaScript
server: {
  cors: { origin: ['https://my-app.test'] },
}

Never use cors: true with host: true on an untrusted network if you can avoid it. It lets any web page read your source files through the dev server.

HTTPS in development

Some browser features, such as service workers outside localhost, the clipboard API on a LAN address, geolocation, and secure cookies, need a secure context. localhost counts as secure; an address like http://192.168.1.20:5173 does not. To use HTTPS, give Vite a certificate:

JavaScript
import fs from 'node:fs';

export default defineConfig({
  server: {
    https: {
      key: fs.readFileSync('./certs/localhost-key.pem'),
      cert: fs.readFileSync('./certs/localhost.pem'),
    },
  },
});

Create trusted local certificates with a tool such as mkcert (mkcert -install once, then mkcert localhost 192.168.1.20) so the browser does not warn. The plugin @vitejs/plugin-basic-ssl generates a self-signed certificate automatically, but browsers show a warning that you must click through.

Note that when the page is on HTTPS, calls to an http:// API are mixed content and blocked. Use the proxy: the browser talks HTTPS to Vite, and Vite talks plain HTTP to your backend.

HMR behind a proxy or HTTPS

If the page is served through another reverse proxy (for example https://dev.example.com forwarding to Vite), HMR's WebSocket must use the public address:

JavaScript
server: {
  hmr: { protocol: 'wss', host: 'dev.example.com', clientPort: 443 },
}

Symptoms of a wrong value: the console shows WebSocket connection to 'ws://localhost:5173' failed and edits only appear after a manual reload.

A tiny CORS model

This runnable model shows what the browser checks and why the proxy avoids it.

Node.js Stand-in: same-origin or cross-origin?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does server.proxy avoid CORS errors in development?

    CORS applies to cross-origin browser requests. With a proxy the browser only talks to the Vite origin.
  2. 2. The front end calls /api/users but the backend route is /users. Which option fixes this?

    rewrite changes the path before forwarding, so /api/users becomes /users.
  3. 3. Which option is needed to proxy a WebSocket on a path?

    ws: true proxies WebSocket upgrade requests for that rule.
  4. 4. Your page is on https:// and fetches http://localhost:8000/api directly. What happens?

    HTTPS pages cannot call insecure HTTP URLs. Let the proxy forward the request from the Vite server.

Summary

  • A cross-origin request needs CORS headers; server.proxy makes browser calls same-origin by forwarding them from the dev server.
  • Keys are prefixes or ^regexes; options include target, changeOrigin, rewrite, secure, ws and configure.
  • Watch prefix collisions such as /api matching /apikey.
  • server.https with mkcert certificates provides a secure context; proxy to HTTP backends to avoid mixed content.
  • Behind another proxy, set server.hmr host, protocol and clientPort so HMR reconnects.

Next: Static Assets and the public Directory