Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

webpack-mock-server

Yegorich5553.6kMIT1.0.23TypeScript support: included

Mocks api requests for webpack-dev-server with hot-replacement

webpack, mock, mocker, server, api, webpack-dev-server, typescript, ts, js, json, hot, replacement, hmr, express, middleware

readme

Webpack Mock Server

ExpressJs Middleware for webpack-dev-server with built-in hot-replacement (HMR) and Typescript compiler. Uses for mocking api responses

npm version install size npm downloads License: MIT

Features

  • Typescript support (>=v2.7): supports .js, .ts, .json files
  • ES6+ export/import support
  • Hot replacement support (auto rebuild on related file changes)
  • Does not require proxy-path-pattern (because this is middleware that pipes routes to splitted server without direct proxy settings)
  • Can be used without webpack (because this is expressjs middleware)
  • Shows every configured response in user-friendly index.html (just click on mock-server-url in console after as mockServer is started: http://localhost:8081 by default)
  • Don't change API routes: use ordinary fetch('/api/getUserInfo') instead of fetch('http://localhost:8081/api/getUserInfo'). Despite on mock-server is hosted on another port, it adds proxy to webpack

Installing

Using npm (installing Typescript is required even if you don't use ts files):

npm i --save-dev webpack-mock-server typescript @types/express

Demo

You can find example of real usage in repo web-react (see /components/account folder)

Examples

Usage with defaults

// webpack.config.js - webpack v5+
const webpackMockServer = require("webpack-mock-server");

module.exports = {
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      webpackMockServer.use(devServer.app, {
        port: (devServer.options.port || 8080) + 1,
      });
      return middlewares;
    },
  },
};

// webpack.mock.ts - feel free to mock responses yourself
import webpackMockServer from "webpack-mock-server";
import nodePath from "path";

// app is express application
export default webpackMockServer.add((app, helper) => {
  // you can find more about express here: https://expressjs.com/
  app.get("/testGet", (_req, res) => {
    res.json("JS get-object can be here. Random int:" + helper.getRandomInt());
  });
  app.post("/testPost", (_req, res) => {
    res.json("JS post-object can be here");
  });

  // you can return any file easy. Example for json response from file:
  app.get("/testResponseFromJsonFile", (_req, res) => {
    res.sendFile(nodePath.join(__dirname, "./response.json"));
  });
});

// multiple exports are supported
export const result = webpackMockServer.add((app, helper) => {
  app.delete("/testDelete", (_req, res) => {
    res.json("JS delete-object can be here. Random int:" + helper.getRandomInt());
  });
  app.put("/testPut", (_req, res) => {
    res.json("JS put-object can be here");
  });
});

Usage with multiple/custom entries (instead of default webpack.mock.ts)

// webpack.config.js
const webpackMockServer = require("webpack-mock-server");

module.exports = {
  devServer: {
   setupMiddlewares: (middlewares, devServer) => {
        webpackMockServer.use(devServer.app, { // MockServerOptions here
          entry: [ // exact fileNames are expected (no wildcard or folder - use custom tsConfig instead)
              "api/users.mock.ts",
              "api/goods.mock.js"
          ],
          before: (req, res, next) => { // you can use this for custom-logging instead of logResponses: true, logRequests: true
              console.log(`Got request: ${req.method} ${req.url}`);
              res.once("finish", () => {
                 console.log(`Sent response: ${req.method} ${req.url}`);
               })
              next();
          }
      });
      return middlewares;
    }
  }
}

// api/users.mock.ts
... // take the example for ts-file above

// api/goods.mock.js
export default webpackMockServer.add((app, helper) => {
  app.get("/testGetGoods", (_req, res) => {
    res.json([{
        id: helper.getRandomInt(1, 999),
        name: "pen"
    }]);
  });
})

Usage with multiple entries by pattern (wildcard)

// webpack.config.js
const webpackMockServer = require("webpack-mock-server");

// for webpack v5
module.exports = {
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      webpackMockServer.use(devServer.app, {
          /* set an empty-array or null to [entry], so entry will be defined
              from 'files' and 'includes' sections in [tsConfigFileName] */
          entry: [],
          tsConfigFileName: "mock/tsconfig.json" // use a different tsconfig-file that is contained entries
      });
      return middlewares;
    }
  }
}

// for webpack v4
module.exports = {
  devServer: {
    before: app =>
      webpackMockServer.use(app, {
          /* set an empty-array or null to [entry], so entry will be defined
              from 'files' and 'includes' sections in [tsConfigFileName]
          */
          entry: [],
          tsConfigFileName: "mock/tsconfig.json" // use a different tsconfig-file that is contained entries
      })
  }
}


// ./mock/tsconfig.json
{
  /*
   *  this is ordinary tsconfig file that overrides every option from [extends] - main tsconfig-file
   */
  "extends": "../tsconfig.json", // you can point the main tsconfig file or remove that property if it's not required
  "include": [  // wildcard-pattern is supported
      "../mock/*",
      "*.mock.ts",
      "**/global.d.ts",
  ],
  "files": [], // beside 'include' option you can point exact files here
  "exclude": ["*test.mock.ts"] // note: exclude option can override 'include' and 'files' options
}

Usage without webpack

As Express middleware: http://expressjs.com/en/guide/using-middleware.html

// webpack.config.js
const webpackMockServer = require("webpack-mock-server");

const express = require('express');
const app = express();

webpackMockServer.use(app, {/*mockServerOptions*/})
...
app.listen(1782);

// webpack.mock.ts - example you can find above
...

Usage with the whole default config

for webpack v5

Details about webpack-dev-server v5 vs v4 see here

// webpack.config.js
...
const webpackMockServer = require("webpack-mock-server");

module.exports = {
  devServer: {
    setupMiddlewares: (middlewares, devServer) => { // it's different for webpack v4
      webpackMockServer.use(devServer.app, {
          port: (devServer.options.port || 8080) + 1, // app searches for free port (starts searching from pointed)
          verbose: false, // send info via console.log
          logRequests: false,
          logResponses: false,
          before: undefined, //can be used for logging
          entry: ["webpack.mock.ts"],
          tsConfigFileName: "tsconfig.json",
          compilerOptions: { // typescript.CompilerOptions that override tsconfig.json:[compilerOptions]
              strictNullChecks: false,
              noImplicitAny: false,
              noUnusedLocals: false,
              noUnusedParameters: false,
              skipLibCheck: true,
              resolveJsonModule: true,
          },
          strictCompilerOptions: { // these options impossible to override
              outDir: "" // used the following: {os.tmpdir()}/webpack-mock-server/{new Date().getTime()}
              rootDir: process.cwd(),
              noEmit: false,
              noEmitHelpers: false,
              esModuleInterop: true,
              module: ts.ModuleKind.CommonJS,
              declaration: false,
              moduleResolution: ModuleResolutionKind.Node10,
              target: defineTarget() // it defines target-ES based on NODE version
          }
      });
      return middlewares;
    }
  }
}

// webpack.mock.ts - example you can find above
...

for webpack v4

// webpack.config.js
...
const webpackMockServer = require("webpack-mock-server");

module.exports = {
  devServer: {
    before: app => // it's different for webpack v5
      webpackMockServer.use(app, {
          port: 8081, // app searches for free port (starts searching from pointed)
          verbose: false, // send info via console.log
          logRequests: false,
          logResponses: false,
          before: undefined, //can be used for logging
          entry: ["webpack.mock.ts"],
          tsConfigFileName: "tsconfig.json",
          compilerOptions: { // typescript.CompilerOptions that override tsconfig.json:[compilerOptions]
              strictNullChecks: false,
              noImplicitAny: false,
              noUnusedLocals: false,
              noUnusedParameters: false,
              skipLibCheck: true,
              resolveJsonModule: true
          },
          strictCompilerOptions: { // these options impossible to override
              outDir: "" // used the following: {os.tmpdir()}/webpack-mock-server/{new Date().getTime()}
              rootDir: process.cwd(),
              noEmit: false,
              noEmitHelpers: false,
              esModuleInterop: true,
              module: ts.ModuleKind.CommonJS,
              declaration: false,
              moduleResolution: ModuleResolutionKind.Node10,
              target: defineTarget() // it defines target-ES based on NODE version
          }
      })
  }
}

// webpack.mock.ts - example you can find above
...

Options

Note: Every path-file-name in options has to be pointed relative to the currentWorkingDirectory (process.cwd() in NodeJs) or point an absolute path

Param Type Default Description
entry String, String[], null ["webpack.mock.ts"] Entry points for typescript-compiler (exact fileNames are expected). Set an empty array or null for using files, include and exlcude sections from tsConfigFileName. Otherwise these sections are ignored!
port Number 8079 App searches for free port (starts searching from pointed)
verbose Boolean false Show debug info in NodeJs via console.log
logResponses Boolean false Show responses-info in NodeJs via console.log
logRequests Boolean false Show request-info in NodeJs via console.log
before (req, res, next) => void undefined Execute custom middleware prior to all other middleware internally within the server Can be used for custom-logging. Example here
compilerOptions typescript.CompilerOptions ... See the latest example above
strictCompilerOptions typescript.CompilerOptions ... readOnly. See the latest example above. These options impossible to override
tsConfigFileName String "tsconfig.json" Pointer to typescript config file. Example here:

MockServerHelper. Methods



Troubleshooting

  • It's important to install Typescript even if use only JS-files (webpack-mock-server uses ts-compiler for gathering ts,js,json files)
  • Don't use NodeJs require operator as dynamic to relative path. Use dirname in this case or absolute path (dirname is changed during the compilation)
  • NodeJs caches every required module (file), so you maybe interested in clearing cache for require(.json)*. Use delete require.cache[require.resolve({yourPathName})] before you call require({yourPathName});
  • Mockserver can't compile the TS-code. Possible reason: you have some extra import OR missed some global files (like global.d.ts). Solution: all mock-files must be without dependencies (imports) of components defined in the main-project files
    • If you have custom tsconfig.mock.json file check if all required \*d.ts files are included .. include: ["**/global.d.ts", ..] ..
    • To check what's wrong use compilation trace npx tsc --project tsconfig.mock.json --generateTrace traceDir OR enable logging via webpack-mock-server option verbose:true
// Wrong
app.get("/testResponseFromJsonFile", (_req, res) => {
  res.sendFile(require.resolve("./response.json"));
});

app.get("/testResponseFromJsonFile2", (_req, res) => {
  res.json(require("./response.json"));
});

// Correct
import nodePath from "path";

app.get("/testResponseFromJsonFile", (_req, res) => {
  res.sendFile(nodePath.join(__dirname, "./response.json"));
});

app.get("/testResponseFromJsonFile2", (_req, res) => {
  /* From NodeJs v8.9.0 you can use options: path
   * const resolvedPath = require.resolve("./response.json", { paths: [__dirname] });
   */
  const resolvedPath = require.resolve(nodePath.join(__dirname, "./response.json"));
  // removing NodeJS cache for getting the latest file
  delete require.cache[resolvedPath];
  res.json(require(resolvedPath));
});
/* Your ordinary http responses from UI */

// Wrong
function apiGetUserInfo() {
  return fetch("http://localhost:8081/api/getUserInfo"); // it works if webpack-mock-server hosted under 8081 port, but it's not correct usage
}

// Correct
function apiGetUserInfo() {
  return fetch("/api/getUserInfo"); // so if you run webpack-devServer with webpack-mock-server data returns webpack-mock-server if route exists; but if build your project then your API will be here
}

changelog

1.0.23 (March 11, 2025)

  • fixed req.body contains unparsed formData nested properties with dot-notation

1.0.22 (October 16, 2024)

  • fixed not running on recent webpack-dev-server versions
  • fixed req.body contains unparsed Date json values
  • fixed req.body contains unparsed formData primitives & Date

1.0.21 (December 29, 2023)

  • fixed crash on tsconfig.json changes

1.0.20 (December 28, 2023)

  • added support for global types defined in custom *.d.ts files

1.0.19 (November 16, 2023)

  • updated examples for webpack 5 according to recent webpack changes (Readme.md)

1.0.18 (April 26, 2023)

  • updated packages
  • fixed ordinary string isn't supported in JSON

1.0.17 (July 05, 2022)

  • updated packages
  • fixed File upload doesn't work for files with russian letters

1.0.16 (May 12, 2022)

1.0.15 (November 2, 2021)

  • added support uploading files with auto-storing to memory and mapping to routes (for retrieving back)

1.0.14 (September 2, 2021)

1.0.13 (July 14, 2021)

  • fixed webpack throws EADDRINUSE after restarting with webpack-mock-server
  • fixed webpack-mock-server does not run if webpack gets EADDRINUSE

1.0.12 (July 14, 2021)

  • fixed sometimes old response after recompilation

1.0.11 (July 12, 2021)

  • removed console.warn added previously for debugging

1.0.8 (June 23, 2021)

  • fixed wrong http-code (was 201 instead of inherited)

1.0.7 (June 23, 2021)

  • fixed case when https is selected in devServer

1.0.6 (May 5, 2021)

  • added inbox supporting of popular body types as json/form-urlencoded/text/multipart-form-data (mostly for post/put requests)
  • moved package @types/express to dependencies (for ts/js-intellisense)
  • updated packages

1.0.5 (March 16, 2020)

  • fixed vulnerabilities in packages

1.0.4 (March 5, 2020)

  • updated README: point on NodeJs require.cache and how we can delete it

1.0.3 (February 13, 2020)

  • fixed post/put does not work and returns httpCode: 405

1.0.2 (February 10, 2020)

  • fixed res.once should be before next() for avoiding missing res.once event for logging purpose

1.0.1 (February 7, 2020)

  • fixed server does not provide favicon via directToServer response
  • fixed default logger catches exception and does not provide actual response
  • fixed \_\_dirname under wepback is not absolute

1.0.0 (February 7, 2020)

  • BREAKING CHANGE: improve export for NodeJs-require (use require('...') instead of require('...').default)
  • options: add .logResponse, .logRequest, .before
  • options.entry: add 'single string' support. Add type and wildcard checking
  • mockServerHelper: implement with methods getRandomInt, getUniqueIdInt
  • webpackMockServer: add '.add' and '.defaultOptions' to export
  • fixed sometimes mock-server overrides webpack port
  • fixed \_\_dirname provides tmpName instead of sourceName
  • fixed mockServerOptions: put noEmitHelpers and esModuleInterop to strictCompilerOptions
  • fixed memory liquid on infinite handling 'process.on' events (each reloading from tsCompiler)
  • fixed piping for routes with optional parameters

0.0.4 (January 31, 2020)

  • fixed entry option does not override tsCompiler rootNames

0.0.3 (January 31, 2020)

  • add README and CHANGELOG
  • add support of multiple exports from mock-files
  • fixed wrong definition of outputFilePath when used **import \* from '../importedFile'** (with '../' in path)
  • fixed there is no index.html in installed package

0.0.2 (January 28, 2020)

  • fixed verbose option is ignored
  • fixed server does not provide updated data
  • prettify index.html for url '/' (getRoutes)
  • improve logging
  • add full-support of tsconfig.json (including 'files' and 'includes' sections)

0.0.1 (January 21, 2020)

  • create basic configuration
  • implement basic functionality