npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

vite-mock-api

v1.0.2

Published

Mocking api server in vite.

Downloads

3

Readme

:gear: Vite Mock API Plugin

vite-mock-api is a Vite plugin that allows you to easily create and manage mock API endpoints for development. By defining simple mock handlers, you can simulate API responses without needing a separate backend, improving development speed and efficiency.

Features

  • Easy Mock API Setup: Just define your mock API handlers in a dedicated folder.
  • Automatic Bundling: Uses esbuild to bundle mock handlers from TypeScript to CommonJS.
  • Middleware Integration: Registers mock endpoints as middleware in the Vite development server.
  • Development-Only Activation: The plugin runs only in development mode and does not affect production builds.
  • Enhanced Request Handling: Parses query parameters and request bodies automatically.
  • Supports Custom Middleware: Allows adding third-party middleware (e.g., body-parser).
  • File Watching: Automatically reloads mock handlers when changes are detected. (watching {mockFilesDir}/index.ts, default mockFilesDir = "mock-api")

Installation

To install the plugin, run:

npm install -D vite-mock-api

or

yarn add -D vite-mock-api

or

pnpm add -D vite-mock-api

Usage

To use the plugin, import it and add it to your Vite configuration file (vite.config.ts).

Example Configuration

Basic usage.

import { defineConfig } from "vite";
import mockApiPlugin from "vite-mock-api";

export default defineConfig({
  plugins: [mockApiPlugin()],
  // default mockFilesDir = "mock-api"
});

Add plugin option.

export default defineConfig({
  plugins: [
    mockApiPlugin({
      mockFilesDir: "my-mock-api", // Optional: Change the mock API directory
      middlewares: [], // Optional: Add custom middleware functions
    }),
  ],
});

Setting Up Your Mock API Handlers

  1. Create a /{mockFilesDir} Directory: In the root of your project, create a directory called {mockFilesDir}.

    (default mockFilesDir = "mock-api")

  2. Define Your API Handlers: Inside the {mockFilesDir} folder, create an index.ts file and export mock handlers.

Example Handler

// my-mock-api/index.ts

import {
  MockHandler,
  MockApiHandlerRequest,
  MockApiHandlerResponse,
} from "vite-mock-api";

const helloHandler: MockHandler = {
  path: "/api/hello",
  handler: (req: MockApiHandlerRequest, res: MockApiHandlerResponse) => {
    console.log(req.headers, req.query, req.params); // check your terminal console.
    res.json({ message: "Hello, world!" }); // check your web console.
  },
};

export default [helloHandler];

Test above Request handler

A request to:

GET http://localhost:5173/api/hello?name=John

will result in the following response:

{
  "message": "Hello, world!"
}

How It Works

  1. The plugin scans the /{mockFilsDir}/index.ts file when the Vite development server starts.
  2. It bundles the mock handlers into a CommonJS module using esbuild.
  3. The bundled mock handlers are dynamically imported and registered as middleware in the Vite dev server.
  4. Requests matching the specified paths are intercepted and handled by the mock handlers.
  5. The plugin watches for changes in the mock API files and reloads the handlers automatically.

Request & Response Enhancements

  • Query Parameters: Automatically parsed and available in req.query and req.params.
  • Request Body: Automatically parsed and accessible via req.body.
  • Custom JSON Response: The response object has a json(data) method for sending JSON responses.
  • Custom Middleware: Allows third-party middleware (e.g., body-parser) to be added before mock API handlers.

Custom Middleware Support

If you want request with body(POST, PATCH, PUT method) request, you can add middleware functions to process requests before they reach mock handlers. See example code below.

Example Using body-parser

import bodyParser from "body-parser";
import mockApiPlugin from "vite-mock-api";

export default defineConfig({
  plugins: [
    mockApiPlugin({
      middlewares: [bodyParser.json()],
    }),
  ],
});

Troubleshooting

  • Missing Mock Handlers: Ensure your /{mockFilesDir} directory and index.ts file exist.
  • Development Mode: The plugin only runs in development mode (vite or npm run dev).
  • Bundling Issues: If esbuild fails, check your console logs for error messages.
  • Correct Export Format: Your index.ts file should export an array of handlers as the default export.
  • File Watching Not Working: Ensure the file path is correctly set in mockFilesDir.

License

This plugin is licensed under the MIT License.

Contributing

Contributions are welcome! If you have suggestions, find issues, or want to add features, feel free to open an issue or submit a pull request.

Author