Mocking Server-Sent Events

Intercept and mock Server-Sent Events (SSE).

Mock Service Worker ships with a first-class API for intercepting and mocking Server-Sent Events (SSE) via the sse namespace provided by the library:

import { sse } from 'msw'

sse

API reference for the `sse` namespace.

Difference from http

The stream of server events is still a regular HTTP connection, which means you can intercept and mock with the http namespace as you would any other HTTP request:

import { http } from 'msw'
 
export const handlers = [
  http.get('/stream', ({ request }) => {
    const stream = new ReadableStream({
      start(controller) {
        controller.enqueue(new TextEncoder().encode('data: Hello World\n\n'))
        controller.close()
      },
    })
 
    return new Response(stream, {
      headers: {
        connection: 'keep-alive',
        'content-type': 'text/event-stream',
        'cache-control': 'no-cache',
      },
    })
  }),
]

Handling SSE via the http namespace, however, has a number of disadvantages:

  • You have to manually construct the stream;
  • You have to encode sent messages and make sure they adhere to the standard;

In comparison, the sse namespace provides you a type-safe, high-level experience of working with SSE:

import { sse } from 'msw'
 
export const handlers = [
  sse<{ message: string }>('/stream', ({ client }) => {
    client.send({ data: 'hello world' })
 
    queueMicrotask(() => {
      client.close()
    })
  }),
]

The implementation details of the comnunication, such as managing the stream and queuing messages, are abstracted away, allowing you to focus on describing the network behavior you want. The sse namespace also enables additional feature otherwise unavailable when working with EventSource directly, such as forwarding of the original server events with ambiguous names.

Next steps

The following sections will guide you through everything you need to know about intercepting and mocking Server-Sent Events:

Intercepting sources

Intercepting and handling event sources.

Server events

Mocking Server-Sent Events.