noopServiceWorkerMiddleware.js 1.1 KB

12345678910111213141516171819202122232425
  1. // A dev-only middleware that resets service workers for the current host:port
  2. // This is for dealing with cases where a developer loads the dev and prod
  3. // versions of an app on the same host:port combination, causing the prod
  4. // service worker to hijack subsequent visists in dev mode.
  5. // Note this doesn't always immediately fix the problem - if the server used
  6. // to serve the production app has a long cache header for /service-worker.js,
  7. // this noop service worker will not be able to take effect. In such cases,
  8. // the developer will have to manually unregister the service worker in
  9. // Chrome Devtools -> Application -> Service Workers
  10. const fs = require('fs')
  11. const path = require('path')
  12. const resetScript = fs.readFileSync(path.resolve(__dirname, 'noopServiceWorker.js'), 'utf-8')
  13. module.exports = function createNoopServiceWorkerMiddleware () {
  14. return function noopServiceWorkerMiddleware (req, res, next) {
  15. if (req.url === '/service-worker.js') {
  16. res.setHeader('Content-Type', 'text/javascript')
  17. res.send(resetScript)
  18. } else {
  19. next()
  20. }
  21. }
  22. }