Vite Plugin for API Mock Server
vite-plugin-mock-dev-server is a Vite plugin designed to provide a lightweight, flexible, and fast API mock development server. It is currently stable at version 2.1.1 and receives frequent updates, including new features and bug fixes. Key differentiators include its non-intrusive, non-injection-based approach to mocking, full TypeScript support, Hot Module Replacement (HMR) for mock files, and pure ES Module architecture since version 2.0.0. The plugin automatically imports mock files from designated directories (default `mock` folder) and supports various content types for responses (text, JSON, buffer, stream). It integrates seamlessly with Vite's `server.proxy` configuration and allows the use of `viteConfig.define` and environment variables within mock definitions. Advanced features like WebSocket mocking, request recording/replay, error simulation, and the ability to build small, independent deployable mock services further enhance its utility for front-end development workflows.
Common errors
-
Error: [plugin:vite-plugin-mock-dev-server] Failed to load config from ...vite.config.js: vite-plugin-mock-dev-server is not a function
cause Attempting to `require` the plugin in a CommonJS-style Vite configuration file when the package is ESM-only.fixEnsure your `vite.config.js` uses ES Module syntax (e.g., `import mockDevServerPlugin from 'vite-plugin-mock-dev-server'`) and potentially change the file extension to `.mjs` or ensure your Node.js environment correctly handles ESM. -
Error: mock file does not contain a default export or 'defineMock' call.
cause A mock file (e.g., `mock/my-api.mock.ts`) is missing the `export default defineMock(...)` structure.fixEnsure every mock file exports its definitions using `export default defineMock({...})` or `export default defineMock([...])`. -
GET http://localhost:5173/api/my-endpoint 404 (Not Found)
cause The mock API endpoint is not being intercepted by the mock server, often due to misconfigured `server.proxy` or incorrect `url` matching in the mock definition.fixVerify that `server.proxy` in `vite.config.ts` includes a rule that matches `/api/my-endpoint` (e.g., `'^/api': { target: '...' }`). Also, check the `url` property in your `defineMock` call to ensure it precisely matches the requested path, including any path parameters.
Warnings
- breaking Version 2.0.0 introduced pure ES Module (ESM) support. This means CommonJS `require()` syntax is no longer directly supported for importing the plugin or its utilities. Projects must use `import` statements.
- breaking The underlying `path-to-regexp` library was upgraded from v6 to v8 in version 2.0.0. This might introduce breaking changes in how path patterns are parsed, especially concerning special characters or complex regular expressions. Refer to the `path-to-regexp` official documentation for specific migration details.
- breaking Version 2.0.0 added a new `dir` configuration option to specify the directory for mock files, relative to `cwd`. While it defaults to `mock`, if you previously relied on a different implicit behavior or custom configuration, this might affect mock file discovery.
- gotcha The plugin requires Node.js version 20 or higher, or version 22 or higher, as specified in its `engines` field. Using older Node.js versions will prevent the plugin from installing or running correctly.
- gotcha For the mock server to intercept requests, you must configure `server.proxy` in your `vite.config.ts` with a target matching your mock URLs. The plugin reads this configuration to enable mock matching. If `server.proxy` is missing or misconfigured, mocks will not be active.
Install
-
npm install vite-plugin-mock-dev-server -
yarn add vite-plugin-mock-dev-server -
pnpm add vite-plugin-mock-dev-server
Imports
- mockDevServerPlugin
const mockDevServerPlugin = require('vite-plugin-mock-dev-server')import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
- defineMock
import defineMock from 'vite-plugin-mock-dev-server'
import { defineMock } from 'vite-plugin-mock-dev-server' - mockDevServerPluginOptions
import type { MockDevServerPluginOptions } from 'vite-plugin-mock-dev-server'
Quickstart
import { defineConfig } from 'vite';
import mockDevServerPlugin from 'vite-plugin-mock-dev-server';
export default defineConfig({
plugins: [
mockDevServerPlugin({
// Optional: Specify mock files directory, relative to cwd.
// dir: 'mocks',
// Optional: Enable/disable the plugin entirely.
enabled: process.env.NODE_ENV === 'development'
}),
],
// 'define' fields are accessible within mock files.
define: {
__APP_VERSION__: JSON.stringify('1.0.0'),
},
server: {
proxy: {
// The plugin reads `server.proxy` to determine which URLs to mock.
// Requests matching '/api' will be handled by the mock server if enabled.
'^/api': {
target: 'http://localhost:3000', // Actual backend or a placeholder
changeOrigin: true,
},
},
},
});
// mock/users.mock.ts
import { defineMock } from 'vite-plugin-mock-dev-server';
export default defineMock([
{
url: '/api/users',
method: 'GET',
body: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
],
delay: 500, // Simulate network latency
},
{
url: '/api/users/:id',
method: 'GET',
body: ({ params }) => ({ id: Number(params.id), name: `User ${params.id}` }),
// Persist mock data on HMR to avoid data loss during development
persistOnHMR: true
},
{
url: '/api/error',
method: 'GET',
status: 500,
body: { message: 'Internal Server Error' },
}
]);