Using Webpack’s Development Server to Proxy API Requests to Servers running Mulitple Websites


Webpack-dev-server enables you to serve web applications during development. To work around the restrictions imposed by CORS, webpack-dev-server ships with a proxy feature that enables the transparent forwarding of requests made to the webpack-dev-server to remote servers. For example, in order to forward everything under /api to http://myserver.com/api, you can simply setup the following proxy config:

{
  "/api": {
     "target": "http://myserver.com'"
   }
}

As described in the documentation, it is also possible to rewrite the request URLs, if neccessary. However, when trying to use the proxy feature to connect to a server that is running multiple webservers on a single IP address, you will quickly find out that the proxy feature is always contacting the default host. The reason for this is that the current version of the webpack-dev-server does not properly set the Host HTTP header. This, in turn, breaks SNI (Server Name Indication) in SSL. Thus, when using webpack-dev-server to communicate with a webserver that is not setup as the default host, you will see errors like this one:

[HPM] Error occurred while trying to proxy request /api/version from localhost:4200 to https://myserver.com (ERR_TLS_CERT_ALTNAME_INVALID) (https://nodejs.org/api/errors.html#errors_common_system_errors)

The solution is fairly trival, you simply have to set the Host header to the name of the webserver that you want to talk to. Unfortunately, this is not described at all in the documentation, so here is how you do it:

{
  "/api": {
     "target": "http://myserver.com'"
     "headers": {
       "Host":"myserver.com"
     }
   }
}