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

Package detail

webpack-dev-middleware

webpack58.8mMIT7.4.2TypeScript support: included

A development middleware for webpack

webpack, middleware, development

readme

npm node tests coverage discussion size

webpack-dev-middleware

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

[!WARNING]

We do not recommend installing this module globally.

Usage

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

app.use(
  middleware(compiler, {
    // webpack-dev-middleware options
  }),
);

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

See below for an example of use with fastify.

Options

Name Type Default Description
methods Array [ 'GET', 'HEAD' ] Allows to pass the list of HTTP request methods accepted by the middleware
headers Array|Object|Function undefined Allows to pass custom HTTP headers on each request.
index boolean|string index.html If false (but not undefined), the server will not respond to requests to the root URL.
mimeTypes Object undefined Allows to register custom mime types or extension mappings.
mimeTypeDefault string undefined Allows to register a default mime type when we can't determine the content type.
etag boolean| "weak"| "strong" undefined Enable or disable etag generation.
lastModified boolean undefined Enable or disable Last-Modified header. Uses the file system's last modified value.
cacheControl boolean|number|string|Object undefined Enable or disable setting Cache-Control response header.
cacheImmutable boolean\ undefined Enable or disable setting Cache-Control: public, max-age=31536000, immutable response header for immutable assets.
publicPath string undefined The public path that the middleware is bound to.
stats boolean|string|Object stats (from a configuration) Stats options object or preset name.
serverSideRender boolean undefined Instructs the module to enable or disable the server-side rendering mode.
writeToDisk boolean|Function false Instructs the module to write files to the configured location on disk as specified in your webpack configuration.
outputFileSystem Object memfs Set the default file system which will be used by webpack as primary destination of generated files.
modifyResponseData Function undefined Allows to set up a callback to change the response data.

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

methods

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

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

headers

Type: Array|Object|Function Default: undefined

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

or

webpackDevMiddleware(compiler, {
  headers: () => {
    return {
      "Last-Modified": new Date(),
    };
  },
});

or

webpackDevMiddleware(compiler, {
  headers: (req, res, context) => {
    res.setHeader("Last-Modified", new Date());
  },
});

or

webpackDevMiddleware(compiler, {
  headers: [
    {
      key: "X-custom-header",
      value: "foo",
    },
    {
      key: "Y-custom-header",
      value: "bar",
    },
  ],
});

or

webpackDevMiddleware(compiler, {
  headers: () => [
    {
      key: "X-custom-header",
      value: "foo",
    },
    {
      key: "Y-custom-header",
      value: "bar",
    },
  ],
});

index

Type: Boolean|String Default: index.html

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

mimeTypes

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.

mimeTypeDefault

Type: String
Default: undefined

This property allows a user to register a default mime type when we can't determine the content type.

etag

Type: "weak" | "strong"
Default: undefined

Enable or disable etag generation. Boolean value use

lastModified

Type: Boolean Default: undefined

Enable or disable Last-Modified header. Uses the file system's last modified value.

cacheControl

Type: Boolean | Number | String | { maxAge?: number, immutable?: boolean } Default: undefined

Depending on the setting, the following headers will be generated:

  • Boolean - Cache-Control: public, max-age=31536000000
  • Number - Cache-Control: public, max-age=YOUR_NUMBER
  • String - Cache-Control: YOUR_STRING
  • { maxAge?: number, immutable?: boolean } - Cache-Control: public, max-age=YOUR_MAX_AGE_or_31536000000, also , immutable can be added if you set the immutable option to true

Enable or disable setting Cache-Control response header.

cacheImmutable

Type: Boolean Default: undefined

Enable or disable setting Cache-Control: public, max-age=31536000, immutable response header for immutable assets (i.e. asset with a hash like image.a4c12bde.jpg). Immutable assets are assets that have their hash in the file name therefore they can be cached, because if you change their contents the file name will be changed. Take preference over the cacheControl option if the asset was defined as immutable.

publicPath

Type: String Default: output.publicPath (from a configuration)

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.

stats

Type: Boolean|String|Object Default: stats (from a configuration)

Stats options object or preset name.

serverSideRender

Type: Boolean
Default: undefined

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

writeToDisk

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);
  },
});

outputFileSystem

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 });

modifyResponseData

Allows to set up a callback to change the response data.

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

middleware(compiler, {
  // Note - if you send the `Range` header you will have `ReadStream`
  // Also `data` can be `string` or `Buffer`
  modifyResponseData: (req, res, data, byteLength) => {
    // Your logic
    // Don't use `res.end()` or `res.send()` here
    return { data, byteLength };
  },
});

API

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

close(callback)

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

Parameters

callback

Type: Function Required: No

A function executed once the middleware has stopped watching.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

setTimeout(() => {
  // Says `webpack` to stop watch changes
  instance.close();
}, 1000);

invalidate(callback)

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

Parameters

callback

Type: Function Required: No

A function executed once the middleware has invalidated.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

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

  // Recompile the bundle with the banner plugin:
  instance.invalidate();
}, 1000);

waitUntilValid(callback)

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

Parameters

callback

Type: Function Required: No

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

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

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

getFilenameFromUrl(url)

Get filename from URL.

Parameters

url

Type: String Required: Yes

URL for the requested file.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

instance.waitUntilValid(() => {
  const filename = instance.getFilenameFromUrl("/bundle.js");

  console.log(`Filename is ${filename}`);
});

FAQ

Avoid blocking requests to non-webpack resources.

Since output.publicPath and output.filename/output.chunkFilename can be dynamic, it's not possible to know which files are webpack bundles (and they public paths) and which are not, so we can't avoid blocking requests.

But there is a solution to avoid it - mount the middleware to a non-root route, for example:

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

// Mounting the middleware to the non-root route allows avoids this.
// Note - check your public path, if you want to handle `/dist/`, you need to setup `output.publicPath` to `/` value.
app.use(
  "/dist/",
  middleware(compiler, {
    // webpack-dev-middleware options
  }),
);

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

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 express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const isObject = require("is-object");
const middleware = require("webpack-dev-middleware");

const app = new express();

// 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:
  res.send(`
<html>
  <head>
    <title>My App</title>
    <style>
    ${normalizeAssets(assetsByChunkName.main)
      .filter((path) => path.endsWith(".css"))
      .map((path) => outputFileSystem.readFileSync(path.join(outputPath, path)))
      .join("\n")}
    </style>
  </head>
  <body>
    <div id="root"></div>
    ${normalizeAssets(assetsByChunkName.main)
      .filter((path) => path.endsWith(".js"))
      .map((path) => `<script src="${path}"></script>`)
      .join("\n")}
  </body>
</html>
  `);
});

Support

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 discussions 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 :bug:, 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.

Other servers

Examples of use with other servers will follow here.

Connect

const connect = require("connect");
const http = require("http");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = connect();

app.use(devMiddleware(compiler, devMiddlewareOptions));

http.createServer(app).listen(3000);

Router

const http = require("http");
const Router = require("router");
const finalhandler = require("finalhandler");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const router = Router();

router.use(devMiddleware(compiler, devMiddlewareOptions));

var server = http.createServer((req, res) => {
  router(req, res, finalhandler(req, res));
});

server.listen(3000);

Express

const express = require("express");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = express();

app.use(devMiddleware(compiler, devMiddlewareOptions));

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

Koa

const Koa = require("koa");
const webpack = require("webpack");
const webpackConfig = require("./webpack.simple.config");
const middleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = new Koa();

app.use(middleware.koaWrapper(compiler, devMiddlewareOptions));

app.listen(3000);

Hapi

const Hapi = require("@hapi/hapi");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {};

(async () => {
  const server = Hapi.server({ port: 3000, host: "localhost" });

  await server.register({
    plugin: devMiddleware.hapiPlugin(),
    options: {
      // The `compiler` option is required
      compiler,
      ...devMiddlewareOptions,
    },
  });

  await server.start();

  console.log("Server running on %s", server.info.uri);
})();

process.on("unhandledRejection", (err) => {
  console.log(err);
  process.exit(1);
});

Fastify

Fastify interop will require the use of fastify-express instead of middie for providing middleware support. As the authors of fastify-express recommend, this should only be used as a stopgap while full Fastify support is worked on.

const fastify = require("fastify")();
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};

(async () => {
  await fastify.register(require("@fastify/express"));
  await fastify.use(devMiddleware(compiler, devMiddlewareOptions));
  await fastify.listen(3000);
})();

Hono

import webpack from "webpack";
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import devMiddleware from "webpack-dev-middleware";
import webpackConfig from "./webpack.config.js";

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};

const app = new Hono();

app.use(devMiddleware.honoWrapper(compiler, devMiddlewareOptions));

serve(app);

Contributing

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

CONTRIBUTING

License

MIT

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

7.4.2 (2024-08-21)

Bug Fixes

7.4.1 (2024-08-20)

Bug Fixes

7.4.0 (2024-08-15)

Features

  • added the cacheImmutable option to cache immutable assets (assets with a hash in file name like image.e12ab567.jpg) (5ed629d)
  • allow to configure the Cache-Control header (#1923) (f7529c3)

Bug Fixes

  • support devServer: false (b443f4d)

7.3.0 (2024-07-18)

Features

7.2.1 (2024-04-02)

Bug Fixes

  • avoid extra log

7.2.0 (2024-03-29)

Features

7.1.1 (2024-03-21)

Bug Fixes

7.1.0 (2024-03-19)

Features

  • prefer to use fs.createReadStream over fs.readFileSync to read files (ab533de)

Bug Fixes

7.0.0 (2023-12-26)

⚠ BREAKING CHANGES

  • minimum supported Node.js version is 18.12.0 (#1694)
  • updated memfs@4 (#1693)

Features

  • minimum supported Node.js version is 18.12.0 (#1694) (e273d61)

6.1.1 (2023-05-16)

Bug Fixes

6.1.0 (2023-05-03)

Features

Bug Fixes

6.0.2 (2023-03-19)

Bug Fixes

6.0.1 (2022-11-28)

Bug Fixes

  • update schema for index and methods properties (#1397) (cda328e)

6.0.0 (2022-11-20)

⚠ BREAKING CHANGES

  • minimum supported webpack version is 5.0.0
  • minimum supported Nodejs version is 14.15.0

5.3.3 (2022-05-18)

Bug Fixes

5.3.2 (2022-05-17)

Bug Fixes

5.3.1 (2022-02-01)

Bug Fixes

5.3.0 (2021-12-16)

Features

5.2.2 (2021-11-17)

Chore

  • update schema-utils package to 4.0.0 version

5.2.1 (2021-09-25)

  • internal release, no visible changes and features

5.2.0 (2021-09-24)

Features

5.1.0 (2021-09-09)

Features

  • don't read full file if Range header is present (e8b21f0)
  • output more information on errors (#1024) (7df9e44)

Bug Fixes

  • reduced package size by removing mem package (#1027) (0d55268)

5.0.0 (2021-06-02)

⚠ BREAKING CHANGES

  • minimum supported Node.js version is 12.13.0 (#928) (4cffeff)

4.3.0 (2021-05-19)

Features

Bug Fixes

4.2.0 (2021-05-10)

Features

  • allow the headers option to accept function (#897) (966afb3)

4.1.0 (2021-01-15)

Features

4.0.4 (2021-01-13)

Bug Fixes

4.0.3 (2021-01-12)

Bug Fixes

  • output stats to stdout instead stderr, how does webpack-cli, if you need hide stats from output please use { stats: false } or { stats: 'none' } (4de0f97)
  • colors are working for stats (4de0f97)
  • schema description (#783) (f9ce2b2)
  • skip Content-type header on unknown types (#809) (5c9eee5)

4.0.2 (2020-11-10)

Bug Fixes

  • compatibility with the headers option (#763) (7c4cac5)

4.0.1 (2020-11-09)

Bug Fixes

  • compatibility with connect (b83a1db)

4.0.0 (2020-10-28)

⚠ BREAKING CHANGES

  • export in CommonJS format

Bug Fixes

  • compatibility with new webpack@5 API (#737) (f6054a0)
  • handle the auto value of the publicPath option (9b4c5ec)
  • support webpack@5 (#702) (9ccc327)

4.0.0-rc.3 (2020-07-14)

  • internal improvements

4.0.0-rc.2 (2020-06-30)

Bug Fixes

  • prefer mime type option over built-in (#670) (7fa2c15)

4.0.0-rc.1 (2020-02-20)

Bug Fixes

4.0.0-rc.0 (2020-02-19)

Bug Fixes

  • respect output.path and output.publicPath options from the configuration
  • respect the stats option from the configuration
  • respect the watchOptions option from the configuration
  • the writeToDisk option now correctly works in multi-compiler mode
  • the outputFileSystem option now correctly works in multi-compiler mode
  • respect [hash]/[fullhash] in output.path and output.publicPath
  • handle exceptions for filesystem operations
  • the Content-Type header doesn't have charset=utf-8 value for custom MIME types and MIME types which can be non utf-8

Features

  • validate options
  • migrate on the webpack logger
  • migrate on the memfs package
  • improve performance

BREAKING CHANGES

  • minimum supported Node.js version is 10.13.0
  • the default value of the option publicPath is taken from the value of the output.publicPath option from the configuration (webpack.config.js)
  • the stats option was removed, the default value of the stats option is taken from the value of the stats option from the configuration (webpack.config.js)
  • the watchOptions was removed, the default value of the watchOptions option is taken from the value of the watchOptions option from the configuration (webpack.config.js)
  • the Content-Type header doesn't have charset=utf-8 value for custom MIME types and MIME types which can be non utf-8
  • the fs option was renamed to the outputFileSystem option
  • the lazy option was removed without replacement
  • the logger, logLevel and logTime options were removed without replacement. You can setup the level value using { infrastructureLogging: { level: 'warn' } }, please read https://webpack.js.org/configuration/other-options/#infrastructurelogging. You can use the infrastructurelog (infrastructureLog in webpack@5) hook to customize logs. The log property in the middleware context was renamed to logger
  • the mimeTypes option first requires you to specify an extension and then a content-type - { mimeTypes: { phtml: 'text/html' } }
  • the force option from the mimeTypes option was removed without replacement
  • the reporter option was removed without replacement
  • the getFilenameFromUrl method was removed from the API
  • the middleware locals now under res.locals.webpack - use res.locals.webpack.stats for access stats and res.locals.webpack.outputFileSystem to access outputFileSystem

3.7.2 (2019-09-28)

Bug Fixes

3.7.1 (2019-09-03)

Bug Fixes

  • directly used mkdirp instead of through Webpack (#436) (dff39a1)
  • displayStats only logged (#427) (98deaf4)
  • the writeToFile option has compatibility with webpack@5 (#459) (5c90e1e)

3.7.0 (2019-05-15)

Features

3.6.2 (2019-04-03)

Bug Fixes

  • check existence of res.getHeader and set the correct Content-Type (#385) (56dc705)

3.6.1 (2019-03-06)

Bug Fixes

  • do not overwrite Content-Type if header already exists (#377) (b2a6fed)

3.5.2 (2019-02-06)

Bug Fixes

3.5.1 (2019-01-17)

Bug Fixes

  • remove querystring from filenames when writing to disk (#361) (90d0d94)

3.5.0 (2019-01-04)

Bug Fixes

  • middleware: do not add 'null' to Content-Type (#355) (cf4d7a9)

Features

  • allow to redefine mimeTypes (possible to use force option) (#349) (e56a181)

3.3.0 (2018-09-10)

Features

  • middleware: expose the memory filesystem (response.locals.fs) (#337) (f9a138e)

3.2.0 (2018-08-23)

Bug Fixes

  • package: 18 security vulnerabilities (#329) (5951de9)

Features

  • middleware: add methods option (options.methods) (#319) (fe6bb86)