Configuration and the dev server

Vite · Practical · 12 min

Most real projects need aliases and a proxy to talk to their backend during development.

vite.config.ts (or .js/.mjs) exports a config object, ideally wrapped in defineConfig for type hints. It can also export a function receiving { command, mode } to vary settings between serve and build.

Frequently used options:

  • plugins: framework and feature plugins, e.g. react().
  • resolve.alias: map @ to src/ so imports become @/components/Button. Mirror it in tsconfig.json paths for TypeScript (or use the resolve.tsconfigPaths option / a plugin).
  • base: the public path when the app is deployed under a sub-path, e.g. /docs/.
  • server.port, server.host (true to listen on all addresses), server.open, server.strictPort.
  • server.proxy: forward API calls to your backend, avoiding CORS in development. changeOrigin: true rewrites the Host header; rewrite adjusts paths; ws: true proxies WebSockets.
  • server.allowedHosts: hosts other than localhost (for tunnels or containers) must be listed.
  • build.outDir, build.sourcemap, and preview options that mirror server.

Vite restarts the dev server automatically when the config file changes. The dev server is for development only: it is not hardened and should never be exposed to the internet.

Example

// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { fileURLToPath, URL } from "node:url";

export default defineConfig(({ command, mode }) => ({
  plugins: [react()],
  resolve: {
    alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) },
  },
  server: {
    port: 3000,
    proxy: {
      // /api/users -> http://localhost:8000/users
      "/api": {
        target: "http://localhost:8000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  build: { sourcemap: mode === "staging" },
  base: command === "build" ? "/app/" : "/",
}));

Remember

  • defineConfig gives typed config; a function form sees command and mode
  • Aliases need matching tsconfig paths
  • server.proxy forwards API calls and avoids CORS in dev
  • Set base when deploying under a sub-path

Watch out for

  • Exposing the dev server publicly as if it were a production server.

Check yourself

  1. What does a `server.proxy` entry for `/api` solve during development?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vite.dev/config/server-options