A development middleware for webpack

License: MIT

Language: JavaScript

Keywords: middleware, webpack, webpack-dev-middleware

npm node deps tests coverage chat size


An express-style development middleware for use with webpack bundles and allows for serving of the files emitted from webpack. This should be used for development only.

Some of the benefits of using this middleware include:

  • No files are written to disk, rather it handles files in memory
  • If files changed in watch mode, the middleware delays requests until compiling has completed.
  • Supports hot module reload (HMR).

Getting Started

First thing's first, install the module:

npm install webpack-dev-middleware --save-dev

Note: We do not recommend installing this module globally.


const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const compiler = webpack({
  // webpack options
const express = require('express');
const app = express();

  middleware(compiler, {
    // webpack-dev-middleware options

app.listen(3000, () => console.log('Example app listening on port 3000!'));


The middleware accepts an options Object. The following is a property reference for the Object.


Type: Array
Default: [ 'GET', 'HEAD' ]

This property allows a user to pass the list of HTTP request methods accepted by the server.


Type: Object
Default: undefined

This property allows a user to pass custom HTTP headers on each request. eg. { "X-Custom-Header": "yes" }


Type: Boolean|String
Default: index.html

If false (but not undefined), the server will not respond to requests to the root URL.


Type: Object
Default: undefined

This property allows a user to register custom mime types or extension mappings. eg. mimeTypes: { phtml: 'text/html' }.

Please see the documentation for mime-types for more information.


Type: String Default: output.publicPath

The public path that the middleware is bound to. Best Practice: use the same publicPath defined in your webpack config. For more information about publicPath, please see the webpack documentation.


Type: Boolean
Default: undefined

Instructs the module to enable or disable the server-side rendering mode. Please see Server-Side Rendering for more information.


Type: Boolean|Function
Default: false

If true, the option will instruct the module to write files to the configured location on disk as specified in your webpack config file. Setting writeToDisk: true won't change the behavior of the webpack-dev-middleware, and bundle files accessed through the browser will still be served from memory. This option provides the same capabilities as the WriteFilePlugin.

This option also accepts a Function value, which can be used to filter which files are written to disk. The function follows the same premise as Array#filter in which a return value of false will not write the file, and a return value of true will write the file to disk. eg.

const webpack = require('webpack');
const configuration = {
  /* Webpack configuration */
const compiler = webpack(configuration);

middleware(compiler, {
  writeToDisk: (filePath) => {
    return /superman\.css$/.test(filePath);


Type: Object
Default: memfs

Set the default file system which will be used by webpack as primary destination of generated files. This option isn't affected by the writeToDisk option.

You have to provide .join() and mkdirp method to the outputFileSystem instance manually for compatibility with webpack@4.

This can be done simply by using path.join:

const webpack = require('webpack');
const path = require('path');
const myOutputFileSystem = require('my-fs');
const mkdirp = require('mkdirp');

myOutputFileSystem.join = path.join.bind(path); // no need to bind
myOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind

const compiler = webpack({
  /* Webpack configuration */

middleware(compiler, { outputFileSystem: myOutputFileSystem });


webpack-dev-middleware also provides convenience methods that can be use to interact with the middleware at runtime:


Instructs a webpack-dev-middleware instance to stop watching for file changes.



Type: Function

A function executed once the middleware has stopped watching.


Instructs a webpack-dev-middleware instance to recompile the bundle. e.g. after a change to the configuration.

const webpack = require('webpack');
const compiler = webpack({ ... });
const middleware = require('webpack-dev-middleware');
const instance = middleware(compiler);


setTimeout(() => {
  // After a short delay the configuration is changed and a banner plugin is added
  // to the config
  compiler.apply(new webpack.BannerPlugin('A new banner'));

  // Recompile the bundle with the banner plugin:
}, 1000);


Executes a callback function when the compiler bundle is valid, typically after compilation.



Type: Function

A function executed when the bundle becomes valid. If the bundle is valid at the time of calling, the callback is executed immediately.

const webpack = require('webpack');
const compiler = webpack({ ... });
const middleware = require('webpack-dev-middleware');
const instance = middleware(compiler);


instance.waitUntilValid(() => {
  console.log('Package is in a valid state');

Known Issues

Multiple Successive Builds

Watching will frequently cause multiple compilations as the bundle changes during compilation. This is due in part to cross-platform differences in file watchers, so that webpack doesn't loose file changes when watched files change rapidly. If you run into this situation, please make use of the TimeFixPlugin.

Server-Side Rendering

Note: this feature is experimental and may be removed or changed completely in the future.

In order to develop an app using server-side rendering, we need access to the stats, which is generated with each build.

With server-side rendering enabled, webpack-dev-middleware sets the stats to res.locals.webpack.devMiddleware.stats and the filesystem to res.locals.webpack.devMiddleware.outputFileSystem before invoking the next middleware, allowing a developer to render the page body and manage the response to clients.

Note: Requests for bundle files will still be handled by webpack-dev-middleware and all requests will be pending until the build process is finished with server-side rendering enabled.

Example Implementation:

const webpack = require('webpack');
const compiler = webpack({
  // webpack options
const isObject = require('is-object');
const middleware = require('webpack-dev-middleware');

// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
function normalizeAssets(assets) {
  if (isObject(assets)) {
    return Object.values(assets);

  return Array.isArray(assets) ? assets : [assets];

app.use(middleware(compiler, { serverSideRender: true }));

// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
  const { devMiddleware } = res.locals.webpack;
  const outputFileSystem = devMiddleware.outputFileSystem;
  const jsonWebpackStats = devMiddleware.stats.toJson();
  const { assetsByChunkName, outputPath } = jsonWebpackStats;

  // Then use `assetsByChunkName` for server-side rendering
  // For example, if you have only one main chunk:
    <title>My App</title>
      .filter((path) => path.endsWith('.css'))
      .map((path) => outputFileSystem.readFileSync(path.join(outputPath, path)))
    <div id="root"></div>
      .filter((path) => path.endsWith('.js'))
      .map((path) => `<script src="${path}"></script>`)


We do our best to keep Issues in the repository focused on bugs, features, and needed modifications to the code for the module. Because of that, we ask users with general support, "how-to", or "why isn't this working" questions to try one of the other support channels that are available.

Your first-stop-shop for support for webpack-dev-server should by the excellent documentation for the module. If you see an opportunity for improvement of those docs, please head over to the webpack.js.org repo and open a pull request.

From there, we encourage users to visit the webpack Gitter chat and talk to the fine folks there. If your quest for answers comes up dry in chat, head over to StackOverflow and do a quick search or open a new question. Remember; It's always much easier to answer questions that include your webpack.config.js and relevant files!

If you're twitter-savvy you can tweet #webpack with your question and someone should be able to reach out and lend a hand.

If you have discovered a 🐛, have a feature suggestion, or would like to see a modification, please feel free to create an issue on Github. Note: The issue template isn't optional, so please be sure not to remove it, and please fill it out completely.


Please take a moment to read our contributing guidelines if you haven't yet done so.




Project Statistics

Sourcerank 20
Repository Size 2.27 MB
Stars 1,994
Forks 308
Watchers 23
Open issues 4
Dependencies 975
Contributors 93
Tags 49
Last updated
Last pushed

Top Contributors See all

renovate[bot] Tobias Koppers Kees Kluskens Andrew Powell Evilebot Tnawi Yuta Hiroto Michael Ciniawsky CT Wu Johannes Ewald Garth Poitras Yu Qi Runrioter Wung Henry Zhu James George Li Yi Matt Edelman Alex Hancock Simen Brekken Ingwie Phoenix Daniel Mohns

Packages Referencing this Repo

A development middleware for webpack
Latest release 4.0.0-rc.1 - Published - 1.99K stars
A development middleware for webpack
Latest release 4.0.0-rc.1 - Updated - 1.99K stars
A development middleware for webpack
Latest release 2.0.4 - Published - 1.99K stars
Offers a koa@2 dev middleware for webpack, which arguments a live bundle to a directory
Latest release 0.0.1 - Published - 1.99K stars
Offers a dev middleware for webpack, which arguments a live bundle to a directory
Latest release 1.5.1 - Published - 1.99K stars

Recent Tags See all

v4.0.0-rc.1 February 20, 2020
v4.0.0-rc.0 February 19, 2020
v3.7.2 September 28, 2019
v3.7.1 September 03, 2019
v3.7.0 May 15, 2019
v3.6.2 April 03, 2019
v3.6.1 March 06, 2019
v3.6.0 February 19, 2019
v3.5.2 February 06, 2019
v3.5.1 January 17, 2019
v3.5.0 January 04, 2019
v3.4.0 September 24, 2018
v3.3.0 September 10, 2018
v3.2.0 August 23, 2018
v3.1.3 April 26, 2018

Interesting Forks See all

Offers a dev middleware for webpack, which arguments a live bundle to a directory
JavaScript - MIT - Updated - 1 stars

Something wrong with this page? Make a suggestion

Last synced: 2019-09-28 15:40:18 UTC

Login to resync this repository