How to setup a webpack dev server using both historyApiFallback and proxying remote api requests?
In Express middleware stack order matters.
Proxy should be set up at webpack config first than historyApiFallback
, this is how it should look like:
devServer:{
contentBase: 'src/www', //Relative directory for base of server
devtool: 'eval',
hot: true, //Live-reload
inline: true,
port: 3000, //Port Number
host: 'localhost', //Change to '0.0.0.0' for external facing server
proxy: {
'^\/users|sitters|bookings': {
target: 'http://127.0.0.1:3001',
rewrite: function(req) {
req.url = req.url.replace(/^\/api/, '');
}
}
},
historyApiFallback: true
},
So of course proxy can be changed to any pattern or regex as an application needs it. In my case that's what I needed.
I end up with following solution:
const REMOTE_URL = process.env.REMOTE_URL || 'http://localhost:8090/';
const config = {
output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true,
contentBase: './app',
proxy: [{
context: '/api',
target: REMOTE_URL,
pathRewrite: {
'^/api' : '/'
}
}]
}
};
So all request to http://locahost:port/api/
goes through proxy, and /api
rewrited.
For example http.get('/api/users')
go to just /users
.
Btw. Object inside proxy is just http-proxy-middleware configuration.