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 🙏

© 2026 – Pkg Stats / Ryan Hefner

connect-mock-api

v1.2.0

Published

Fake API server and middleware for connect and express

Readme

Connect Mock API

Express / Connect middleware for programmable fake APIs

Installation

npm install connect-mock-api --save

Usage as an express/connect middleware

const express = require('express');
const mockApiMiddleware = require('connect-mock-api').middleware;

const app = express();

const mocks = mockApiMiddleware({
    baseUrl: '', //optional
    endpoints: [
        //... endpoints configuration object here, see below
    ]
});

app.use(mocks);
app.listen(8000);

Endpoint Configuration

Endpoints are objects with the following properties:

  • method (string): The expected methods of the incoming request (default: GET),
  • path (string|regexp|function): the path to match relative to the root URL. If a function it must return a string or a regular expression (default: null),
  • delay (number|function): force a delay in milliseconds for the response. If a function it must return a number (default: 0),
  • contentType (string): Response content type (default: application/json),
  • template (*|function): Response body template. Could be any type of content in relation to the ContentType parameter. If a function it will be executed with a params object and the endpoint itself as arguments. (default: null)

Note: The params object contains 3 properties:

  • $req: the original express / connect request object
  • $parsedUrl: The request URL parsed by NodeJS native url.parse method
  • $routeMatch: either an object (when path is a string) or an array of matched segments (when path is a regular expression). See below for details.

Path Matching Formats and $routeMatch

Endpoint's path configuration could be a plain string, a regular expression or a string with Express-like parameters (see path-to-regexp for details).
$routeMatch format will vary based on the provided path:

  • regular expression: $routeMatch will be the resulting array of calling RegExp.prototype.exec on it
  • string or Express-like route: $routeMatch will be and object with named parameters as keys. Note that even numeric parameters will be strings. Examples:
/* Plain string */
{
    
    path: '/api/v1/users'
    // /api/v1/users/ -> $routeMatch === {}
}

/* Express-like path */
{
    path: '/api/v1/users/:id'
    // /api/v1/users/10 -> $routeMatch === {id: '10'}
}

/* RegExp */
{
    path: /^\/api\/v1\/users\/(\d+)$/
    // /api/v1/users/10 -> $routeMatch === ['/api/v1/users/10', '10']
}

Endpoint response template

Any key in the response template could be either a plan value or a function. If a function, it will be executed at response time with a params object and the endpoint itself as arguments.

Note: The params object contains two property:

  • $req: the original express / connect request object
  • $parsedUrl: The request URL parsed by NodeJS native url.parse method
  • $routeMatch: either a boolean (when path is a string) or an array of matched segments (when path is a regular expression)

Endpoint Base URL

The baseUrl configuration option sets up a base URL for every relative endpoint path provided. To override the base URL use absolute URLs.

Note: baseUrl applies just to string paths.

const mocks = mockApiMiddleware({
    baseUrl: '/api/v1/', //optional
    endpoints: [
        {
            // this endpoint will respond at /api/v1/users
            path: 'users',
            template: {
                // ...
            }
        }, {
            // this endpoint will respond at /custom/path
            path: '/custom/path',
            template: {
                // ...
            }
        }
    ]
});

Examples

  1. A basic GET endpoint returning a JSON object
const enpoint = {
    path: '/api/v1/user',
    template: {
        name: 'John',
        surname: 'Doe'
    }
};
  1. A GET endpoint returning a dynamic data provided with Chance

const chance = require('connect-mock-api/lib/utils').chance;

const enpoint = {
    path: '/api/v1/user',
    template: {
        name: () => chance.first(),
        surname: () => chance.last()
    }
};
  1. A GET endpoint matching a regexp and returning a dynamic property based on the match

const chance = require('connect-mock-api/lib/utils').chance;

const enpoint = {
    //matches either a male of female user request
    path: /\/api\/v1\/user\/(male|female)$/,
    template: {
        name: (params) => chance.first({ 
            gender: params.$routeMatch[1]
        }),
        surname: (params) => chance.last({ 
            gender: params.$routeMatch[1]
        })
    }
};
  1. A GET endpoint matching a regexp and returning a dynamic template based on the match

const chance = require('connect-mock-api/lib/utils').chance;

const enpoint = {
    path: '/api/v1/:frag',
    template: (params) => {
        //calling /api/v1/user
        //params.$routeMatch === {'frag': 'user'}
        if (params.$routeMatch.frag === 'user') {
            return {
                name: () => chance.first(),
                surname: () => chance.last()
            };
        }
        
        return {
            error: 'Not matching anything'
        };
        
    }
};
  1. A POST endpoint, accepting a body request and returning a success message

Note: to parse the request body you should append body-parser middleware to the express / connect middleware list.


const enpoint = {
    path: '/api/v1/send',
    method: 'POST',
    template: (params) => {
        if (!params.$req.body.username || !params.$req.body.password) {
            return {
                success: false,
                msg: 'You must provide a username and a password'
            };
        }
        
        return {
            success: true,
            msg: 'Succesfully logged in!'
        };
        
        
    }
};

Contributing

  1. Fork it or clone the repo
  2. Install dependencies npm install
  3. Run npm start to launch a development server
  4. Code your changes and write new tests in the tests folder.
  5. Ensure everything is fine by running npm test and npm run eslint
  6. Push it or submit a pull request :D

Credits

Created by Marco Solazzi

License

MIT