msw: Changes to handlers for node is not being picked up by live reload

Prerequisites

Environment check

  • I’m using the latest msw version
  • I’m using Node.js version 14 or higher

Node.js version

v14.18.2

Reproduction repository

https://github.com/vercel/next.js/tree/canary/examples/with-msw

Reproduction steps

  • Run yarn dev
  • Makes changes to handler for https://my.backend/book
  • Refresh the page
  • Changes made to handler is not being reflected

Current behavior

In msw@0.41.1, this version, changes made to handler was being reflected with live reload. After this version, this does not work anymore. Looks like a regression in versions after this

Expected behavior

Changes made to handler should be reflected without having to stop and start the server like in 0.41.1 version

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 4
  • Comments: 16 (4 by maintainers)

Most upvoted comments

Here is a workaround I found.

import {server} from './server'

export function initMSW() {
  if (typeof window === 'undefined') {
    if ('listeningServer' in globalThis) {
      ;(globalThis as any).listeningServer.close()
    }
    server.listen({
      onUnhandledRequest: 'bypass',
    })
    ;(globalThis as any).listeningServer = server
    console.log('[MSW] Mocking enabled.')
  } else {
    import('./worker').then(({worker}) => {
      return worker.start({
        onUnhandledRequest: 'bypass',
      })
    })
  }
}

Description

Next.js live reload simply re-evaluates the files that have been modified from the top. However, the evaluation is performed on the execution environment in which the previous version of the code was evaluated. In other words, when you do a live reload, any resources that were not released in the previous version are carried over to the next version.

In other words, if a server is listening in the previous version and the application is live-reloaded without closing it, the previous server is still alive and its handler is used in the next version. This is the cause of the problem.

To solve this problem, simply close the previous version of the server when the application is live-reloaded.

Hey @kettanaito, I have created a repo that reproduce that live reload worked with msw@0.41.1 for handlers on server side process of NextJs. That is why I think it is a regression since it used to work. Could we reopen this issue please?

Steps to reproduce:

  • Checkout the above branch on my fork

  • cd examples/with-msw/

  • yarn install

  • yarn dev

  • Trying changing mock response for https://my.backend/book (called in getServerSideProps) and https://my.backend/user (called when clicking on Load Reviews => request to API Routes => which calls https://my.backend/user)

  • When you refresh the page, you should be able to see the updated mock response.

I have also attached a GIF as example Kapture 2022-09-21 at 11 48 13