Prevent Server-to-client Message Forwarding in MSW

By default, once we establish the actual WebSocket server connection in the mock, all the server events will be forwarded to the client. You can opt-out from this default behavior by calling event.preventDefault() on any intercepted server event.

Resources

Share with a coworker

Social Share Links

Transcript

[00:00] By default, when you establish the actual server connection, MSW will forward all client events to that server and all the server events back to the client. That ensures that the two can actually communicate. But you can opt out from that forwarding on the individual message level. To do that, go to the server message listener and call event prevent default. With this change let's head to the browser and try sending a message.

[00:27] Huh, we're not getting anything back but if we inspect the network we can see the server actually sending the confirmation back to the client. But what's happening here is that this confirmation triggers the message event on the server object, and since we are preventing that default message forwarding, it never reaches the client, never reaches our application. This is extremely powerful because now we are in charge of that server event. And one of the things we can do with that event is modify it. So let's use our existing parse chat message utility and provide it the event.data, the actual payload sent from the server.

[01:01] Store the parsing result in a variable called message, check if it's a supported message and if it's not, ignore it. And now to send a modified version of that message to the client, we would need to grab the client reference from the connection listener and call client.send. But before we do, let's modify that message. Let's do message, data, text, and assign it to an uppercase version of that same text. And then use the createChatMessage utility and pass the modified message as the argument.

[01:32] Now when we're going to send a message, like hello world, we will receive an uppercase version of it back. So what's happening here is that the original server sends that confirmation, and this triggers the message event on our server object right here. And then we prevent the default message forwarding from the server to the client by calling event.preventDefault() so then we can modify this message and send it back to the client using the client.send() method, providing a modified message as the argument, And keep in mind that you can prevent that message forwarding conditionally. For example, we can move this event.preventDefault call after checking if the message is supported. This will prevent the forwarding for supported messages so we can modify them, but bypass any other events sent from the server.

[02:18] The client will receive them as-is.