Skip to main content
Version: 2.6.0

Routes Handler

What is a Routes Handler?

A "Routes handler" is the element at charge of handling the routes variants declarations, and sending the appropriate response.

Mocks Server includes only one Routes Handler by default, which accepts routes variants declared in the format described in the routes chapter, but you can add your own route variants formats.

This feature, combined with the plugins development, gives you the possibility of adding to Mocks Server almost every new feature you want.

Creating custom Routes Handlers

A Routes Handler should be defined as a Class containing:

static get id()

This static getter will be used to recognize the Routes Handler. When defining a route variant, the handler to be used can be defined using the handler property. That property in route variants should be the id of the Route Handler to be used.

constructor(route, mocksServer)

  • route: All route and route variants properties from the route definition (method, url, variantId, and all other properties defined in the route variant object).
  • mocksServer: The mocksServer instance.

middleware(req, res, next)

This is the middleware that will be called when the route url matches and the specific variant should be used.

get plainResponsePreview()

This getter should return a plain object containing an approached preview of the response that will be sent when the route variant is used. This is useful to provide information to other plugins or Mocks Server interfaces.


Here you have an example of how a custom Routes Handler should be defined:

// ./CustomRoutesHandler.js

class CustomRoutesHandler {
static get id() {
return "error";

constructor(routeVariant, mocksServer) {
this._error = routeVariant.error;
this._variantId = routeVariant.variantId;
this._mocksServer = mocksServer;

middleware(req, res, next) {`Sending route variant "${this._variantId}"`);
message: this._error.message

get plainResponsePreview() {
return {
body: {
message: this._error.message
status: this._error.code,

module.exports = CustomRoutesHandler;

Then you can add your custom Routes Handler using the mocks.config.js file:

// mocks.config.js

const CustomRoutesHandler = require("./CustomRoutesHandler");

module.exports = {
addRoutesHandlers: [CustomRoutesHandler],
options: {
port: 3100,
mock: "base",
cli: true

You can also add Route Handlers programmatically using the mocksServer.addRoutesHandler method (useful to be used from plugins, for example)

And now, you can use the custom handler when defining route variants:

// mocks/routes/users.js

module.exports = [
id: "get-users",
url: "/api/users",
method: "GET",
variants: [
id: "error-400",
handler: "error", // id of the handler to be used
error: {
code: 400,
message: "Error message",
// This one will use the "default" handler
id: "empty",
response: {
status: 200,
body: []