Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Dev Server and HMR

Dev Server Options

Configure the Vite dev server with server.port, host, open, strictPort, headers, warmup, watch and fs.allow, and learn how to add custom middleware and read the startup output.

The Vite dev server is a small Node.js HTTP server with a lot of behaviour layered on top: it transforms modules, rewrites imports, pushes HMR updates over a WebSocket and falls back to index.html. Most of its behaviour is fine by default. This lesson covers the server options you will actually change, and what the server does when it starts.

Vite is not installed on this site, so the config is read-only. A Node stand-in at the end implements a tiny dev server with the same shape (static files, headers, a fallback) that you can run and read.

The server block

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

export default defineConfig({
  server: {
    port: 3000,
    strictPort: true,
    host: true,
    open: '/dashboard',
    headers: { 'X-Dev-Server': 'vite' },
  },
});

port and strictPort

port sets the starting port (default 5173). If it is busy Vite tries the next ones (5174, 5175...) unless strictPort: true, in which case it exits with an error. Use strictPort when something else (an OAuth redirect URL, a mobile device, a proxy) expects a fixed port.

host

By default the server listens on localhost only. host: true or '0.0.0.0' listens on all network interfaces, so phones and other computers can reach it. A specific address such as '192.168.1.20' binds to one interface. The matching CLI flag is --host. On untrusted networks avoid exposing the dev server: it can read project files.

Since Vite 6, the server also checks the Host header and rejects hosts that are not allowed, which protects against DNS rebinding attacks. If you use a custom domain, a tunnel or a container name, add it:

JavaScript
server: {
  allowedHosts: ['my-app.test', '.ngrok-free.app'], // leading dot allows subdomains
}

open

open: true opens the browser at startup. A string opens a path ('/docs/index.html'). Set the environment variable BROWSER to choose a browser or BROWSER=none to disable opening.

headers

Adds response headers for all dev requests, handy for testing cross-origin isolation (needed by SharedArrayBuffer):

JavaScript
server: {
  headers: {
    'Cross-Origin-Opener-Policy': 'same-origin',
    'Cross-Origin-Embedder-Policy': 'require-corp',
  },
}

cors

CORS for the dev server is enabled for all origins by default (older versions) or limited to localhost in newer versions. Set cors: { origin: 'https://my-site.test' } to be specific; see Proxy, CORS and HTTPS in Development.

warmup

Pre-transforms files you know will be needed so the first page load is faster:

JavaScript
server: {
  warmup: {
    clientFiles: ['./src/main.js', './src/components/*.vue'],
  },
}

watch

Vite watches your project with chokidar. You can ignore noisy folders or switch to polling in environments where file events fail (Docker bind mounts on some systems, network drives, WSL with Windows files):

JavaScript
server: {
  watch: {
    ignored: ['**/generated/**'],
    usePolling: true,
    interval: 300,
  },
}

Polling uses more CPU, so turn it on only when needed.

fs.allow and fs.strict

The dev server serves files with the /@fs/ prefix only from inside the workspace root (the nearest folder with pnpm-workspace.yaml, a workspaces field or a .git folder). If a file outside the root must be served, say a shared package in a monorepo, whitelist it:

JavaScript
server: {
  fs: {
    allow: ['..', '/shared/fonts'],
  },
}

Leave fs.strict on. Turning it off lets the dev server read any file on the machine through the browser.

Startup output and keyboard shortcuts

TEXT
  VITE v7.x.x  ready in 289 ms

  โžœ  Local:   http://localhost:3000/
  โžœ  Network: http://192.168.1.20:3000/
  โžœ  press h + enter to show help

In the terminal, press h then Enter to list shortcuts: r restart the server, u show URLs, o open in browser, c clear the console, q quit. Shortcuts for opening and clearing are also available through the --open and --clearScreen flags.

Custom middleware

The dev server is built on a connect-style middleware stack. A plugin can add its own middleware with the configureServer hook, for example to mock an API:

JavaScript
// vite.config.js
const mockApi = () => ({
  name: 'mock-api',
  configureServer(server) {
    server.middlewares.use('/api/hello', (req, res) => {
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ message: 'Hello from the dev server' }));
    });
  },
});

export default { plugins: [mockApi()] };

Middlewares registered directly in configureServer run before Vite's internal ones (so you can intercept requests). To run after them, return a function from the hook. Plugins have their own chapter.

A tiny dev server you can run

This stand-in is a model of the three behaviours above: serving files, adding headers and the SPA fallback. It does not use the network; it handles fake requests so it runs anywhere.

Node.js Stand-in: static files, headers and fallback

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.

Reading a server problem

Symptom Usual cause Try
Port keeps changing Port busy Set strictPort to see the conflict, or stop the other process
Phone cannot connect Server bound to localhost, or firewall --host and allow the port in the firewall
"Blocked request. This host is not allowed" Using a custom domain or tunnel Add it to server.allowedHosts
Edits are not noticed File events missing (Docker, WSL, network drive) server.watch.usePolling
403 for /@fs/... File outside the allowed root server.fs.allow

A second, even smaller model shows how host choices map to listen addresses:

Node.js Stand-in: what host values mean

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. What does server.strictPort: true do?

    Without strictPort Vite picks the next free port. With it, a busy port is a startup error.
  2. 2. How do you let a phone on the same Wi-Fi open your dev server?

    By default the server listens on localhost only. host: true listens on all network interfaces.
  3. 3. File edits are not detected in a Docker bind mount. What option can fix it?

    Polling checks files on a timer, which works where file system events do not arrive.
  4. 4. You open the dev server through a tunnel domain and see 'Blocked request. This host is not allowed.' What do you set?

    Vite validates the Host header to prevent DNS rebinding. Add your domain to allowedHosts.

Summary

  • server.port, strictPort, host, open and headers control how the dev server starts and responds.
  • allowedHosts protects against rebinding; add custom domains and tunnels to it.
  • warmup pre-transforms hot files; watch can ignore folders or use polling.
  • fs.allow controls which files outside the workspace root the server may serve; keep fs.strict on.
  • Plugins can add middleware with configureServer.

Next: Dependency Pre-Bundling