Skip to content

MSW sometimes still handles requests after worker is stoppedΒ #2597

Description

@diego-aquino

Prerequisites

Environment check

  • I'm using the latest msw version
  • I'm using Node.js version 20 or higher

Browsers

Chromium (Chrome, Brave, etc.)

Reproduction repository

https://github.com/diego-aquino/msw-worker-stop-bypass-issue

Reproduction steps

  1. pnpm install
  2. pnpm test

Current behavior

Starting in msw@2.11.2, I found out that workers sometimes handle requests even after worker.stop() is called.

In the reproduction repository, this expect sometimes passes, sometimes fails.

https://github.com/diego-aquino/msw-worker-stop-bypass-issue/blob/main/example.browser.test.ts#L22-L27

  worker.stop();

  // This expect sometimes passes, sometimes fails.
  await expect(async () => {
    await fetch(`${baseURL}/users`);
  }).rejects.toThrowError(TypeError);

From my tests, I did not see this issue happening with server.close(), neither with worker.stop() and server.close() before 2.11.2 (I tested 2.11.1).

Expected behavior

I expected all requests made after worker.stop() was called to not be handled.

Activity

  1. added
    bugSomething isn't working
    scope:browserRelated to MSW running in a browser
    needs:triageIssues that have not been investigated yet.
    on Sep 27, 2025
  2. changed the title [-]MSW sometimes still handles requests after worker was stopped[/-] [+]MSW sometimes still handles requests after worker is stopped[/+] on Apr 15, 2026
  3. kettanaito commented on Apr 16, 2026

    @kettanaito
    Member

    Released: v2.13.4 πŸŽ‰

    This has been released in v2.13.4.

    Get these changes by running the following command:

    npm i msw@latest
    

    Predictable release automation by Release.

  4. diego-aquino commented on Apr 16, 2026

    @diego-aquino
    Author

    Hi, @kettanaito. I'm not sure that this issue is fixed.

    I upgraded the reproduction repository to msw@2.13.4 and the problem persists.

    Also, the new tests in #2668 still fail non-deterministically even against main:

    pnpm test:browser in-flight-request.test.ts
    
    ...
    
      3 failed
        [chromium] β€Ί test/browser/msw-api/setup-worker/stop/in-flight-request.test.ts:89:3 β€Ί bypasses requests immediately made after the worker was stopped, considering no default response (2) 
        [chromium] β€Ί test/browser/msw-api/setup-worker/stop/in-flight-request.test.ts:89:3 β€Ί bypasses requests immediately made after the worker was stopped, considering no default response (12) 
        [chromium] β€Ί test/browser/msw-api/setup-worker/stop/in-flight-request.test.ts:89:3 β€Ί bypasses requests immediately made after the worker was stopped, considering no default response (23) 
      99 passed (22.6s)
    

    Let me know if you have any recommendations about how to approach this problem. I can help implement/validate/review the fix if you are interested. #2683 looks related.

  5. kettanaito commented on Apr 17, 2026

    @kettanaito
    Member

    @diego-aquino, yeah, you are right. The test is flaky. I've run it multiple times locally before the release, but I can verify that it fails 1/10 times for me. There has to be some race still happening somewhere. I really hope it's just an incorrectly orchestrated test.

    You're saying it's still happening for you. Is that still reproducible on the repo you shared above?

  6. diego-aquino commented on Apr 17, 2026

    @diego-aquino
    Author

    You're saying it's still happening for you. Is that still reproducible on the repo you shared above?

    @kettanaito, unfortunately yes. I updated the repo yesterday and the tests still fail non-deterministically between 1/2 and 2/3 of the time.

    The test itself is very simple:

    for (let testNumber = 1; testNumber <= 100; testNumber++) {
      it(`bypasses requests made after the worker was stopped (test ${testNumber})`, async () => {
        await worker.start({ quiet: true });
    
        let response = await fetch(`${baseURL}/users`);
        expect(response.status).toBe(200);
        expect(await response.json()).toEqual([]);
    
        worker.stop();
    
        // This expect sometimes passes, sometimes fails.
        await expect(async () => {
          await fetch(`${baseURL}/users`);
        }).rejects.toThrowError(TypeError);
      });
    }
    AssertionError: promise resolved "undefined" instead of rejecting
    
    - Expected: 
    Error {
      "message": "rejected promise",
    }
    
    + Received: 
    undefined
    
     ❯ example.browser.test.ts:27:7
         25|     await expect(async () => {
         26|       await fetch(`${baseURL}/users`);
         27|     }).rejects.toThrowError(TypeError);
           |       ^
         28|   });
         29| }
    
     Test Files  1 failed (1)
          Tests  68 failed | 32 passed (100)
       Start at  17:20:40
       Duration  659ms
    
  7. kettanaito commented on Apr 20, 2026

    @kettanaito
    Member

    Would it help if you moved worker.start() outside of the loop in the example above?

    The complexity of properly managing worker.stop() (disabled mode) is starting to annoy me, to be honest. I wonder if all that method should do is prepend a passthrough request handler and be done with it. That would solve any timing issues and produce the same behavior, with the only implication is that requests performed after worker.stop() would still route entirely through the worker (request -> worker -> client -- passthrough --> worker -> response).

    I quite dislike the semantics of .stop() since, despite its name, it's not an opposite action to .start(). Stopping the worker does not, in fact stop the worker as that's a costly procedure and nobody should be starting/stopping a service worker repeatedly anyway. What it was always meant to do (and what it does, in-flight requests aside) is to pause the interception. These are just thoughts for the future, but perhaps this would make more sense:

    • await worker.start(), register and activate the worker;
    • worker.pause(), pause the request interception;
    • await worker.stop(), unregister the worker.

    This could help us communicate behavioral expectations to the end users:

    • pausing the worker handles the in-flight requests as per your handlers;
    • stopping the worker aborts in-flight requests entirely (not a thing yet, might be a thing).

    Raising this in #2723.

  8. kettanaito commented on Apr 20, 2026

    @kettanaito
    Member

    Root cause

    Since our interception is worker-first, there's no way to know when a request happens on the page and whether it happened before or after worker.stop() was called. I've introduced the interceptedAt timestamp in the worker, but there's a race condition:

    It takes time for the request to reach the worker. The interceptedAt timestamp doesn't accurately reflect the request initiator time in relation to worker.stop(). It's possible that a request performed before stop receives a timestamp that's higher than stoppedAt, making MSW think that request has to be passthrough instead of handled.

    The same timing issue applies to the stop before request flow.

    Tracking requests client-side would be against MSW's principles and I'm strongly against that. It makes me think that the actual issue here is the undefined expectations of what is supposed to happen when you call worker.stop(). The original assumption was:

    • handle in-flight requests performed before stopping;
    • passthrough the requests performed after stopping.

    This does make sense, but as I mentioned is impossible to implement reliably in a worker-first architecture. I've also considered the following approaches, but none of them solve the problem:

    • worker.stop() returning a promise with CLIENT_CLOSED_ACK;
  9. kettanaito commented on Apr 20, 2026

    @kettanaito
    Member

    Update

    I found a way to reliably solve this in #2724, but it includes breaking changes in the worker, which means the fix will be available in the next major releaseβ€”3.0. You can always use a WIP build of #2692 if this is blocking you though. That branch is experimental and although I will try my best to keep it stable, things might break so keep that in mind.

    This issue will close when the mentioned fix will merge into feat/3.0 without it being released. There's no reason to keep it open if it cannot be addressed as a patch.

  10. kettanaito commented on Apr 20, 2026

    @kettanaito
    Member

    Closed by #2724.

  11. diego-aquino commented on Apr 20, 2026

    @diego-aquino
    Author

    Hi, @kettanaito. Thanks a lot for the detailed investigation.

    It makes me think that the actual issue here is the undefined expectations of what is supposed to happen when you call worker.stop().

    I agree. My initial assumption was that worker.stop() reverted the results of worker.start(), which is not the case as you've explained.

    • await worker.start(), register and activate the worker;
    • worker.pause(), pause the request interception;
    • await worker.stop(), unregister the worker.

    This could help us communicate behavioral expectations to the end users

    Great! This API looks good to me.

    You can always use a WIP build of #2692 if this is blocking you though.

    Thank you. This is non-blocking for me. I raised it as a separate issue because I was wondering if it was the expected behavior.

  12. locked and limited conversation to collaborators on May 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingscope:browserRelated to MSW running in a browser

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions