fastify-sse-v2 is a Fastify plugin designed to streamline the implementation of Server-Sent Events (SSE) within a Fastify application. It augments the `FastifyReply` object with a `.sse()` method, enabling developers to send individual events or stream events from `AsyncIterable` or `EventEmitter` sources, thereby abstracting the underlying HTTP streaming complexities. The current stable version is 4.2.2, with releases occurring periodically, typically every few months, to address bug fixes and introduce minor features. A primary differentiator is its seamless integration with Fastify's reply object and robust support for modern async/await patterns in event streaming. It also provides configurable options for `retryDelay` to manage client reconnection logic and `highWaterMark` to control internal stream buffering, offering fine-grained control over SSE behavior.
npm install fastify-sse-v2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up a Fastify server with fastify-sse-v2 to stream events using an AsyncIterable source, sending five messages at 1.5-second intervals.
Migrate any logic dependent on the SSE stream's 'end' event to use `request.socket.on('close')` for client disconnection detection.Upgrade your Fastify application to version 4 or higher. Alternatively, for Fastify v3, use `fastify-sse-v2@1.x`.
Ensure `reply.sseContext.source.end()` is called to properly close the SSE stream when sending individual events, especially if the stream is meant to have a finite duration. For client disconnections, listen to `request.socket.on('close')`.Upgrade to `fastify-sse-v2@4.2.2` or newer to mitigate issues with exceptions occurring after headers have been sent.
Upgrade to `fastify-sse-v2@4.2.1` or newer to ensure correct handling of newlines within event data payloads.
Ensure you have called `fastify.register(FastifySSEPlugin);` before attempting to use `reply.sse()`. Also, verify that your Fastify version meets the peer dependency requirement (>=4.0.0 for plugin versions 3.x and above).
Implement checks to ensure the SSE stream is still active before attempting to send new events. For individual events, manage the lifecycle with `reply.sseContext.source.end()`. For `AsyncIterable` or `EventEmitter` sources, ensure your generator or event listener cleans up when the `request.socket.on('close')` event fires.Once `reply.sse()` is called, the response is committed to an SSE stream. Do not attempt to modify headers or send a different type of response on the same request. Ensure all SSE-related logic is handled within the `reply.sse()` context.