In my current setup, I am utilizing BrowserSync in a unique way. I have my web server (Apache in a Docker container) proxied, but I am also serving hot module replacement (HMR) from a Webpack dev server.
In my local development environment, the configuration is as follows:
https://mytestsite.localhost
– Apache service in a Docker container
https://localhost:8888
– Webpack Dev server serving HMR
https://localhost:3000
– BrowserSync`
While hard reloads are working perfectly fine, the issue arises with hot reloads. The document served by the BrowserSync proxy should be reading the hotupdate.json
served by webpack-dev-server. When a hot update is received, the page attempts to load /hotupdate.json
, resulting in a 404 error because the browser is trying to access
https://localhost:3000/hotupdate.json
, whereas the hotupdate.json
is actually served by the Webpack server at https://localhost:8888/hotupdate.json
.
Since I know the absolute URL of this resource, I want to instruct BrowserSync to redirect any requests to /hotupdate.json
to
https://localhost:8888/hotupdate.json
. I have attempted to achieve this using middleware, but I seem to be struggling due to a lack of understanding of Express-style middleware.
Although I have tried implementing some middleware, it has not been successful. Here is an example of my attempt:
browserSync({
proxy: {
target: `https://${process.env.APP_HOST_PATH}`,
middleware: [
dontProxyHotUpdate,
require('webpack-dev-middleware')(bundler, {
noInfo: true,
publicPath: webpackConfig.output.path
}),
]
},
files: [
'app/css/*.css',
'app/*.html'
]
});
function dontProxyHotUpdate (req, res, next){
if(req.url === '/hotupdate.json'){
req.url = 'https://127.0.0.1:8888/hotupdate.json';
}
next();
}
While the middleware is being loaded (as evident from console.log(req.url)
), the request URL is not being rewritten successfully. Possible solutions may involve rewriting the request URL or directly overwriting the response.
It may be questioned why I am not using webpack-dev-server directly, as it already serves HMR effectively. The reason is that it lacks the capability to rewrite anchor elements within a page, such as changing
https://mytestsite.localhost/link
to https://localhost:3000/link
. This rewriting is essential for navigating a site during development and ensuring assets, like SVGs, load properly only if the path, host, and port all match.