Webpack-dev-server: Can I use middleware with webpack-dev-server?

Created on 5 Oct 2015  路  4Comments  路  Source: webpack/webpack-dev-server

I am trying to solve this issue https://github.com/lahmatiy/component-inspector/issues/9#issuecomment-145467810

I tried

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

var app = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true,
  stats: {
    colors: true
  }
});

app.use(function(req, res, next) {
  console.log('Middleware triggered');
  next();
});

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
  }

  console.log('Listening at localhost:3000');
});

with no result.
Can middlewares used with webpack-dev-server somehow?

Most helpful comment

The append middleware would not be triggered as the response already send.
According to this [https://github.com/webpack/webpack-dev-server/commit/6e0e95c5f07751546f1e1db439c68e81be0624ae] commit, you can prepend middlewares like this:

var server = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true,
  setup: function(app) {
    app.use(function(req, res, next) {
      console.log('Middleware triggered');
      next();
    });
  },
  stats: {
    colors: true
  }
});

assign the setup option with a function.

All 4 comments

The append middleware would not be triggered as the response already send.
According to this [https://github.com/webpack/webpack-dev-server/commit/6e0e95c5f07751546f1e1db439c68e81be0624ae] commit, you can prepend middlewares like this:

var server = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true,
  setup: function(app) {
    app.use(function(req, res, next) {
      console.log('Middleware triggered');
      next();
    });
  },
  stats: {
    colors: true
  }
});

assign the setup option with a function.

Thanks! This works

This was helpful to me as well, thanks @chemzqm

This was helpful. FYI for someone It was deprecated like below (here)!

This option is deprecated in favor of devServer.before and will be removed in v3.0.0.

Was this page helpful?
0 / 5 - 0 ratings