Registry / web-framework / fastify-sse-v2

fastify-sse-v2

JSON →
library4.2.2jsnpmunverified

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-v2
INSTALL
IMPORT
SIG · FASTIFY-SSE-V2
F
fastify-sse-v2
web-frameworkjavascriptv4.2.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FastifySSEPlugin
✓ import { FastifySSEPlugin } from 'fastify-sse-v2';
✗ const FastifySSEPlugin = require('fastify-sse-v2');
This is the main named export for registering the plugin. The package primarily uses ESM.
sse
✓ reply.sse({ data: 'hello' });
The `sse` method is added to the `FastifyReply` instance by the plugin and is not directly imported. It's accessible after plugin registration.
FastifyReply and SSE types
✓ import { FastifyInstance, FastifyReply } from 'fastify'; declare module 'fastify' { interface FastifyReply { sse: (payload: { id?: string; event?: string; data: string; retry?: number; comment?: string } | AsyncIterable<{ id?: string; event?: string; data: string; retry?: number; comment?: string }>) => void; sseContext: { source: { end: () => void } }; } }
While types are shipped, extending Fastify's interfaces is a common pattern to ensure TypeScript correctly recognizes the added `sse` method and `sseContext` property on `FastifyReply`.

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.

import Fastify from 'fastify'; import { FastifySSEPlugin } from 'fastify-sse-v2'; const fastify = Fastify({ logger: true }); fastify.register(FastifySSEPlugin); // Helper to simulate async work const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); fastify.get('/events', function (request, reply) { reply.sse( (async function* source() { for (let i = 0; i < 5; i++) { await sleep(1500); const eventData = { id: String(i), data: `Message ${i} at ${new Date().toISOString()}` }; fastify.log.info(`Sending event: ${JSON.stringify(eventData)}`); yield eventData; } fastify.log.info('SSE stream finished.'); })() ); }); const start = async () => { try { await fastify.listen({ port: 3000 }); } catch (err) { fastify.log.error(err); process.exit(1); } }; start();
Debug
Known issues
breakingThe 'end' event, previously emitted when an SSE stream was closing, has been removed. Dependents on this event for cleanup or notification will need to find alternative mechanisms, such as listening to `request.socket.on('close')`.
fix
Migrate any logic dependent on the SSE stream's 'end' event to use `request.socket.on('close')` for client disconnection detection.
affects: >=4.0.0
breakingVersion 3.0.0 dropped support for Fastify v3. This plugin now exclusively requires Fastify v4 or newer. Attempting to use it with Fastify v3 will result in compatibility issues.
fix
Upgrade your Fastify application to version 4 or higher. Alternatively, for Fastify v3, use `fastify-sse-v2@1.x`.
affects: >=3.0.0
gotchaWhen sending individual events using `reply.sse()`, the connection remains open indefinitely. It will only terminate if `reply.sseContext.source.end()` is explicitly called or the client disconnects.
fix
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')`.
affects: >=2.0.0
gotchaExceptions thrown after headers have been sent in the SSE context can lead to unexpected behavior or unhandled errors. Version 4.2.2 introduced a fix for this scenario.
fix
Upgrade to `fastify-sse-v2@4.2.2` or newer to mitigate issues with exceptions occurring after headers have been sent.
affects: <4.2.2
gotchaPrior to version 4.2.1, newlines within event data were not handled properly, potentially corrupting the SSE stream format. This was addressed in `v4.2.1`.
fix
Upgrade to `fastify-sse-v2@4.2.1` or newer to ensure correct handling of newlines within event data payloads.
affects: <4.2.1
Errors
Common errors & fixes
Error: fastify.sse is not a function
The `fastify-sse-v2` plugin was either not registered correctly, or your Fastify instance is too old for the plugin version used.
fix
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).
ERR_STREAM_WRITE_AFTER_END
Attempting to write data to an SSE stream that has already been closed, either explicitly by calling `reply.sseContext.source.end()` or due to client disconnection.
fix
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.
ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client
You are attempting to send HTTP headers (e.g., calling `reply.send()` or similar methods) after the SSE connection has been initiated, which already sends specific headers for SSE.
fix
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.
Upgrade
Version history
4.2.2latest on npm
Audit
Dependencies
fastifyrequiredPeer dependency, required for the plugin to function within a Fastify application.
Agent activity
18 hits · last 30 days
node
14
Bingbot
1
Resources
fastify-sse-v2 — npm install fastify-sse-v2 · libregistry