Skip to content

Conversation

@kettanaito
Copy link
Member

@kettanaito kettanaito commented May 27, 2025

Warning

This change will require you to upgrade your worker script via npm init. If you've saved the worker script location in the past using the --save flag, the worker script will be updated automatically.

Test attempt at #2473. Highly flaky due to how the client registrations are resolved across tabs. I don't believe it's worth it to pursue that test.

@kettanaito
Copy link
Member Author

kettanaito commented May 30, 2025

Hi, @IrishBruse. I hope you don't mind me moving the discussion around the fix here.

Update

Your solution does work but it doesn't account for nested clients (i.e. requests coming from iframes). In those cases, the clientId will point to the child frame and not the frame that has registered the worker (the parent). Thus, the child ID is never be in the activeClientIds, resulting in requests originating from the child frames being unhandled.

That's a pickle because resolving the actual client id is an asynchronous action (we already have the resolveMainClient() utility in the worker) and you cannot cal asynchronous code before event.respondWith(), that's a no-op. Even reading the Client from clientId is an async action.

@kettanaito kettanaito force-pushed the fix/reading-url-of-undefined branch from cd5b912 to 37be6c1 Compare May 30, 2025 15:48
@kettanaito kettanaito added help wanted Extra attention is needed needs:discussion labels May 30, 2025
@kettanaito kettanaito changed the title fix: prevent request handling for unregistered clients feat: prevent request handling for unregistered clients May 30, 2025
@kettanaito
Copy link
Member Author

kettanaito commented May 30, 2025

Update

Since the original proposal breaks the nested frames support, I'm trying to remove the need in context.requests, in the first place. The RESPONSE event from the worker script will now forward the entire serialized request associated with that response. It's a bit more expensive since now it would have to (1) clone the request one more time in order to (2) read its body for the request instance to be properly transferred to the client.

That being said, I don't expect any performance degradation or impact, for that matter, from this change.

@kettanaito kettanaito removed the help wanted Extra attention is needed label May 30, 2025
@kettanaito kettanaito force-pushed the fix/reading-url-of-undefined branch from 0592e6f to 06b1133 Compare May 30, 2025 16:23
@pkg-pr-new
Copy link

pkg-pr-new bot commented May 30, 2025

Open in StackBlitz

npm i https://pkg.pr.new/msw@2510

commit: 06b1133

@kettanaito kettanaito changed the title feat: prevent request handling for unregistered clients feat: send request reference within the RESPONSE event May 30, 2025
@dmezei
Copy link

dmezei commented Jun 2, 2025

I updated my repo to use this build during our tests (vitest browser). This version seem to fix the Cannot read properties of undefined (reading 'url') error. Thanks for the fix!

Note: I've seen the comment about the worker script. In my case no such thing was required. I created this little vite plugin for msw running in the browser:

export const mockServiceWorkerPlugin = (): PluginOption => ({
    name: 'add-mock-server',
    apply: 'serve',
    configureServer: (server) => {
        server.middlewares.use((req, res, next) => {
            if (!req.url?.endsWith('mockServiceWorker.js')) {
                return next();
            }
            res.setHeader('Content-Type', 'text/javascript');
            res.statusCode = 200;
            res.write(readFileSync(resolve('./node_modules/msw/lib/mockServiceWorker.js')));
            res.end();
        });
    },
});

@kettanaito
Copy link
Member Author

@dmezei, thank you so much for confirming!

I was just thinking about making a Vite plugin for MSW's worker yesterday! What a coincidence. Still weighing the pros and cons but thinking it would be worth it. We can have a simple plugin that appends a new route handler to Vite's dev server and make it serve /mockServiceWorker.js from node_modules. No more worker updates!

If you feel like it, you can suggest this as a feature so we can track it. Thanks.

@kettanaito kettanaito merged commit 4256351 into main Jun 2, 2025
19 checks passed
@kettanaito kettanaito deleted the fix/reading-url-of-undefined branch June 2, 2025 18:57
@kettanaito
Copy link
Member Author

Released: v2.9.0 🎉

This has been released in v2.9.0!

Make sure to always update to the latest version (npm i msw@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

'Cannot read properties of undefined (reading 'url')' when multiple browser tabs are open

3 participants