Intercepting sources

Intercepting and handling event sources.

You can intercept any EventSource in your applicatio by defining a request handler for it using the sse namespace. For example, consider this event source:

new EventSource('https://api.example.com/events')

Intercept it by its URL and start handling the connection:

import { sse } from 'msw'
 
export const handlers = [
  sse('https://api.example.com/events', ({ request, client, server }) => {
    client.send({ data: 'hello world' })
  }),
]

Predicate

You can use the same predicate types for Server-Sent Events as you would use for HTTP requests, which includes:

  • Relative URLs;
  • Absolute URLs;
  • Regular expressions.

For example, here’s how you can intercept an EventSource to a remote server with a dynamic path segment id:

sse('https://api.example.com/events/:id', ({ params }) => {
  console.log(params.id)
})

Response resolver

The following properties are available on the response resolver object argument for the sse handler:

PropertyTypeDescription
clientServerSentEventClientIntercepted EventSource client connection object.
serverServerSentEventServerActual EventSource server connection object.
requestRequestFetch API representation of the intercepted request.
requestIdstringUUID representing the intercepted request.
paramsRecord<string, string | string[]>Request path parameters (e.g. :userId).
cookiesRecord<string, string>Parsed request cookies.

Much like Server-Sent Events utilize HTTP, working with the sse namespace has a significant overlap with the http namespace. We highly recommend getting yourself familiar with intercepting HTTP requests with MSW since that will answer a lot of questions you might have around Server-Sent Events.

Intercepting requests

Learn how to intercept outgoing requests.

Next steps

Now that you know how to intercept EventSource connections, it’s time to learn more about handling them (sending mock events, connecting to the real server, etc).

Server events

Mocking Server-Sent Events.