Webpack Proxy with http-proxy-middleware

UPDATE Jan 11, 2016: The PR was merged, webpack-dev-server now uses http-proxy-middleware, so the following code is not needed.

UPDATE Jan 3, 2016: I implemented http-proxy-middleware into the webpack-dev-server project. You can comment on/contribute to the PR here: https://github.com/webpack/webpack-dev-server/pull/359/files

I’ve been using Webpack recently and I am super fond of it. It is the easiest bundler I have used by far. I ran across a problem today however, and want to briefly write about it.

The project I am working on has a back end REST API running on port 8080, and a front end website running on port 8081. Because the project may need to support older browsers (such as IE8), I can’t rely on CORS headers on the API side. The best way to make calls to the API, then, is to use a proxy.

It turns out the Webpack has a proxy functionality build on top of node-http-proxy (NHP), great! Not so fast. My specific use case was that all requests to frontend:8081/api would be forwarded to backend:8080. For example, a request to frontend:8081/api/users/1 should proxy the request to backend:8080/users/1. It turns out that this can’t be done using any combination of configuration at the time of writing.

Well, so much for that. Time to write my own proxy. Luckily, Webpack offers webpack-dev-middleware which allows one to pretty much brew their own webpack-dev-server, though it doesn’t support the inline command line option.

My implementation of the dev server is not super-complete, but it does the job. I’m using http-proxy-middleware as it is a much more configurable proxy library for Node. I’m also using webpack-hot-middleware (not provided by Webpack) for hot reloading and to mimic the inline functionality of the webpack-dev-server.