Webpack as a middleware in Express.js/React application


First of all, this is my very first article. I was going to write it for a very long time but I wanted it to be perfect. Then I realized, it doesn’t have to be. I want to share with you my experience. I know it’s not perfect but having it out there gives me one advantage. Maybe someone has a better idea how to solve the problems I solved and maybe at the end of the day I’ll end up learning something new.


Some time ago I decided to create my first app in React. I chose Webpack as a module bundler mainly because I didn’t have any experience with it. At first I was struggling with the configuration but finally I made it work. There was only one problem. I wanted to have a server in place with an API from where I would pass the data to the client side.

Webpack comes with a development server but I didn’t want to mock the API responses. I wanted to work on server and client side of my application at the same time. I found out that you can use Webpack compiler as a middleware.

With this middleware in place I can work simultaneously on client and server side.

This is how the server file looks like:

const express = require('express'),
app = express(),
webpack = require('webpack'),
webpackDevMiddleware = require('webpack-dev-middleware'),
webpackHotMiddleware = require('webpack-hot-middleware'),
webpackConfig = require('./../webpack.config'),
path = require('path');

let compiler;

webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
stats: {colors: true}
}));

app.use(webpackHotMiddleware(compiler, {
log: console.log
}));

app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'views/index.html'));
});

app.listen(3000, function () {
console.log('Server is running on port 3000');
});

You can check out the full configuration here: https://github.com/bognix/express-react-webpack-boilerplate