Mocking API routes inside the Vite development server
Use a Connect middleware plugin to test same-origin API responses, status codes, latency, and failure states from one Vite dev process.
The API contract was available before the backend was ready. I put a small mock middleware in Vite’s development server so the browser could exercise normal responses and failures from the same origin.
Comparing three mock setups
| Setup | Where requests are handled | When I would use it |
|---|---|---|
| Standalone Express, json-server, or NestJS process | Separate HTTP server | Teams need a mock shared across browsers and other clients |
| Mock Service Worker | Browser service worker | Tests or demonstrations should intercept the network at the browser boundary |
| Vite Connect middleware | Existing development server | A local UI needs predictable same-origin fixtures under one command |
A second HTTP process needs its own port and startup workflow. It may also need a proxy or CORS configuration. A service worker has different lifecycle and cache behavior to debug. The Vite approach keeps the API route on the frontend server’s host and port and starts it with npm run dev.
Registering a Connect middleware at the right point
Connect runs matching middleware in registration order. If a handler calls res.end(), the mock response completes there. If it calls next(), later middleware can handle the requested file or HTML entry. Match both method and path so a mock cannot accidentally take over unrelated requests.
flowchart LR
Browser["Request /api/v1/users/me"] --> ViteDevServer["Vite Dev Server<br/>(Connect Middleware Engine)"]
subgraph MiddlewareChain["Connect middleware chain"]
direction TB
M_Cors["1. corsMiddleware"]
M_CustomMock["Match mock URL"]
M_Transform["Transform ESM"]
M_Static["Serve static files"]
M_Html["5. viteHtmlFallbackMiddleware<br/>(SPA fallback)"]
M_Cors --> M_CustomMock
M_CustomMock -->|"Matched route"| Res["Return JSON"]
M_CustomMock -->|"Call next()"| M_Transform
M_Transform --> M_Static --> M_Html
end
ViteDevServer --> M_Cors
configureServer exposes server.middlewares. Calling use directly within the hook registers middleware before Vite’s internal middleware. Returning a function from the hook instead lets the plugin install middleware after the built-ins. The early registration gives the mock API first chance to handle its own route. Vite configureServer
Implementing delays, responses, and fall-through
I kept transport mechanics in the plugin and moved scenario definitions to a separate handler file. The plugin reads method and path, finds the matching handler, and builds its response. It can delay delivery to exercise loading UI and return non-success codes for error handling.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// plugins/vite-plugin-dev-mock.ts
import type { Plugin, ViteDevServer } from 'vite';
import type { IncomingMessage, ServerResponse } from 'node:http';
export interface MockHandler {
url: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
status?: number;
delay?: number;
response: (req: IncomingMessage, body?: any) => any;
}
export interface DevMockOptions {
prefix?: string;
handlers: MockHandler[];
}
export function devMockPlugin(options: DevMockOptions): Plugin {
const prefix = options.prefix || '/api';
// Parse the HTTP request body
const parseRequestBody = (req: IncomingMessage): Promise<any> => {
return new Promise((resolve) => {
let bodyStr = '';
req.on('data', (chunk) => {
bodyStr += chunk;
});
req.on('end', () => {
try {
resolve(bodyStr ? JSON.parse(bodyStr) : {});
} catch {
resolve(bodyStr);
}
});
});
};
return {
name: 'vite-plugin-dev-mock',
// Run only when serving
apply: 'serve',
configureServer(server: ViteDevServer) {
console.log('\x1b[35m[vite-plugin-dev-mock]\x1b[0m Scanning mock endpoint handlers...');
options.handlers.forEach((h) => {
const methodTag = h.method === 'POST' ? '\x1b[33m[POST]\x1b[0m' : '\x1b[32m[GET]\x1b[0m ';
console.log(` \x1b[32m✔\x1b[0m ${methodTag} ${h.url.padEnd(26)} (delay: ${h.delay || 0}ms, status: ${h.status || 200})`);
});
// Add the mock before Vite's built-in middleware
server.middlewares.use(async (req: IncomingMessage, res: ServerResponse, next: () => void) => {
const reqUrl = req.url?.split('?')[0];
const reqMethod = req.method?.toUpperCase();
if (!reqUrl || !reqUrl.startsWith(prefix)) {
return next(); // Continue through Vite for non-API requests
}
// Match a registered handler
const matchedHandler = options.handlers.find(
(h) => h.url === reqUrl && h.method === reqMethod
);
if (!matchedHandler) {
return next();
}
// Parse the body and simulate latency
const parsedBody = reqMethod !== 'GET' ? await parseRequestBody(req) : undefined;
const delayMs = matchedHandler.delay || 0;
const statusCode = matchedHandler.status || 200;
setTimeout(() => {
const responseData = matchedHandler.response(req, parsedBody);
res.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
'X-Powered-By': 'Vite-Dev-Mock-Plugin',
'X-Mock-Latency': `${delayMs}ms`,
});
res.end(JSON.stringify(responseData, null, 2));
}, delayMs);
});
console.log('\x1b[35m[vite-plugin-dev-mock]\x1b[0m Connect middleware stack initialized successfully.');
},
};
}
A request with no matching mock continues through Vite. The application can still request its modules and static assets normally. A handler can return a dynamic fixture instead of treating every path as a static JSON file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// mock/handlers.ts
import type { MockHandler } from '../plugins/vite-plugin-dev-mock';
export const mockHandlers: MockHandler[] = [
{
url: '/api/v1/health',
method: 'GET',
delay: 0,
status: 200,
response: () => ({ status: 'UP', timestamp: new Date().toISOString() }),
},
{
url: '/api/v1/users/me',
method: 'GET',
delay: 80,
status: 200,
response: () => ({
id: 'usr_9921',
name: 'Namju Kim',
role: 'STAFF_ENGINEER',
department: 'Platform Architecture',
}),
},
{
url: '/api/v1/auth/login',
method: 'POST',
delay: 150,
status: 200,
response: (_req, body) => {
if (body?.email === 'engineer@namju.kim') {
return {
code: 'SUCCESS',
message: 'Authentication succeeded.',
data: {
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.mock_signature',
user: {
id: 'usr_9921',
name: 'Namju Kim',
role: 'STAFF_ENGINEER',
},
},
};
}
return { code: 'UNAUTHORIZED', message: 'The email or password is incorrect.' };
},
},
{
url: '/api/v1/products',
method: 'GET',
delay: 100,
status: 200,
response: () => [
{ id: 'prod_1', name: 'MacBook Pro 16', price: 3690000, stock: 12 },
{ id: 'prod_2', name: 'Studio Display', price: 2090000, stock: 5 },
],
},
{
url: '/api/v1/orders',
method: 'POST',
delay: 200,
status: 201,
response: (_req, body) => ({
orderId: 'ord_' + Date.now(),
totalAmount: body?.amount || 0,
status: 'PAID',
}),
},
];
Register the plugin alongside the frontend plugin in vite.config.ts.
1
2
3
4
5
6
7
8
9
10
11
12
13
// vite.config.ts
import { defineConfig } from 'vite';
import { devMockPlugin } from './plugins/vite-plugin-dev-mock';
import { mockHandlers } from './mock/handlers';
export default defineConfig({
plugins: [
devMockPlugin({
prefix: '/api',
handlers: mockHandlers,
}),
],
});
The mock’s login contract uses sample values only. Keeping the client pointed at a relative /api path makes it easier to switch from local middleware to an actual same-origin backend or proxy.
Verifying the developer workflow
Figure 1. The dev server prints the routes it can mock at startup.
Start npm run dev and send the mock login request with curl to /api/v1/auth/login on the Vite port. The captured example returned HTTP 200 after the configured 154 ms delay. X-Powered-By: Vite-Dev-Mock-Plugin and X-Mock-Latency: 154ms identified the middleware response. A nonmatching request should still reach the rest of the server.
Figure 2. The response uses the frontend server port and shows the simulated delay.
Test more than the success case. A slow reply should keep the loading state visible without leaving duplicate requests behind. An expired session or failed login should cause the expected client behavior. Change representative response fixtures when the API contract changes.
Keeping the mock out of deployment
apply: 'serve' restricts setup to serving, and configureServer itself only applies to Vite’s development server. Check the production output to confirm it contains no route fixture or mock behavior. Development-only credentials and responses should stay behind this boundary. For a team that needs a deployed preview mock, make that a separate and explicitly controlled service.
For richer interactive scenarios, server.ws can carry a local toggle for failures such as HTTP 500 or an expired session. server.watcher can reload mock definitions when their files change. Keep the registry replacement atomic so a request sees a complete old or new definition. Never count on a dev mock to validate authentication or integration with the actual service.
- Confirm file and HMR requests are passed through by the middleware.
- Exercise the success, invalid input, and deliberately delayed branches.
- Build production and check that the mock endpoint does not appear in the deployment path.