Vite Plugin Fake Server

2.2.3 · active · verified Sun Apr 19

vite-plugin-fake-server provides a robust fake server solution for Vite development environments, intercepting both XHR and Fetch requests to simulate API responses. The current stable version is 2.2.3, and the project demonstrates an active release cadence with frequent bug fixes and feature enhancements, including recent compatibility updates for Vite 8. Key differentiators include its agnostic approach to data generation libraries (allowing use of Faker.js, Mock.js, etc.), support for both ESM and CommonJS modules, comprehensive TypeScript typings via `defineFakeRoute`, and compatibility with various file types (`.ts`, `.js`, `.mjs`, etc.). It also supports custom HTTP headers, status codes, and can even be configured for independent deployment, offering flexibility for mocking in both development and production scenarios.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `vite-plugin-fake-server` in `vite.config.ts` and define two fake API routes using `defineFakeRoute` in `fake/user.fake.ts`. One route uses Mock.js, and the other uses Faker.js to generate user data, illustrating the plugin's flexibility. It also includes client-side JavaScript to show how to consume these fake endpoints.

import { defineConfig } from "vite";
import { vitePluginFakeServer } from "vite-plugin-fake-server";
import { faker } from "@faker-js/faker";
import Mock from "mockjs";
import { defineFakeRoute } from "vite-plugin-fake-server/client";

// vite.config.ts
export default defineConfig({
	plugins: [
		vitePluginFakeServer({
			// Optional: specify base directory for fake routes
			include: 'fake',
			// Other options can go here, e.g., enable: true
		}),
	],
});

// fake/user.fake.ts (create this file in the 'fake' directory)
export default defineFakeRoute([
	{
		url: '/mock/get-user-info',
		method: 'GET',
		response: () => {
			return Mock.mock({
				id: '@guid',
				username: '@first',
				email: '@email',
				avatar: '@image("200x200")',
				role: 'admin',
			});
		},
	},
	{
		url: '/fake/get-user-info-faker',
		method: 'GET',
		response: () => {
			return {
				id: faker.string.uuid(),
				avatar: faker.image.avatar(),
				birthday: faker.date.birthdate().toISOString().split('T')[0],
				email: faker.internet.email(),
				firstName: faker.person.firstName(),
				lastName: faker.person.lastName(),
				sex: faker.person.sexType(),
				role: 'user',
			};
		},
	},
]);

// Example client-side usage (e.g., in App.vue or index.ts)
async function fetchUserInfo() {
  try {
    const mockResponse = await fetch('/mock/get-user-info');
    const mockData = await mockResponse.json();
    console.log('Mock.js user info:', mockData);

    const fakerResponse = await fetch('/fake/get-user-info-faker');
    const fakerData = await fakerResponse.json();
    console.log('Faker.js user info:', fakerData);
  } catch (error) {
    console.error('Failed to fetch user info:', error);
  }
}

fetchUserInfo();

view raw JSON →