@fastify/sse 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,12 +2,52 @@ version: 2
2
2
  updates:
3
3
  - package-ecosystem: "github-actions"
4
4
  directory: "/"
5
+ commit-message:
6
+ # Prefix all commit messages with "chore: "
7
+ prefix: "chore"
5
8
  schedule:
6
- interval: "monthly"
9
+ interval: "weekly"
10
+ cooldown:
11
+ default-days: 7
12
+ allow:
13
+ - dependency-name: "*"
14
+ update-types:
15
+ - "version-update:semver-major"
7
16
  open-pull-requests-limit: 10
8
17
 
9
18
  - package-ecosystem: "npm"
10
19
  directory: "/"
20
+ commit-message:
21
+ # Prefix all commit messages with "chore: "
22
+ prefix: "chore"
11
23
  schedule:
12
- interval: "monthly"
24
+ interval: "weekly"
25
+ cooldown:
26
+ default-days: 7
27
+ versioning-strategy: "increase-if-necessary"
28
+ allow:
29
+ - dependency-name: "*"
30
+ update-types:
31
+ - "version-update:semver-major"
32
+ ignore:
33
+ # TODO: remove ignore until neostandard support ESLint 10
34
+ - dependency-name: "eslint"
35
+ - dependency-name: "neostandard"
36
+ - dependency-name: "@stylistic/*"
13
37
  open-pull-requests-limit: 10
38
+ groups:
39
+ # Production dependencies with breaking changes
40
+ dependencies:
41
+ dependency-type: "production"
42
+ # ESLint related dependencies
43
+ dev-dependencies-eslint:
44
+ patterns:
45
+ - "eslint"
46
+ - "neostandard"
47
+ - "@stylistic/*"
48
+ # TypeScript related dependencies
49
+ dev-dependencies-typescript:
50
+ patterns:
51
+ - "@types/*"
52
+ - "tstyche"
53
+ - "typescript"
@@ -14,6 +14,11 @@ on:
14
14
  - 'docs/**'
15
15
  - '*.md'
16
16
 
17
+ # This allows a subsequently queued workflow run to interrupt previous runs
18
+ concurrency:
19
+ group: "${{ github.workflow }}-${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
20
+ cancel-in-progress: true
21
+
17
22
  permissions:
18
23
  contents: read
19
24
 
@@ -22,7 +27,7 @@ jobs:
22
27
  permissions:
23
28
  contents: write
24
29
  pull-requests: write
25
- uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
30
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@v6
26
31
  with:
27
32
  license-check: true
28
33
  lint: true
@@ -0,0 +1,19 @@
1
+ name: Lock Threads
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 0 1 * *'
6
+ workflow_dispatch:
7
+
8
+ concurrency:
9
+ group: lock
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ lock-threads:
16
+ permissions:
17
+ issues: write
18
+ pull-requests: write
19
+ uses: fastify/workflows/.github/workflows/lock-threads.yml@v6
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Matteo Collina
4
+ Copyright (c) 2025-present The Fastify team <https://github.com/fastify/fastify#team>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # @fastify/sse
2
2
 
3
- [![NPM Version](https://img.shields.io/npm/v/@fastify/sse.svg)](https://npmjs.org/package/@fastify/sse)
3
+ [![NPM Version](https://img.shields.io/npm/v/@fastify/sse.svg?style=flat)](https://www.npmjs.com/package/@fastify/sse)
4
4
  [![CI](https://github.com/fastify/sse/workflows/CI/badge.svg)](https://github.com/fastify/sse/actions)
5
+ [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
5
6
 
6
7
  Server-Sent Events plugin for Fastify. Provides first-class SSE support with clean API integration, session management, and streaming capabilities.
7
8
 
@@ -33,11 +34,11 @@ await fastify.register(require('@fastify/sse'))
33
34
  fastify.get('/events', { sse: true }, async (request, reply) => {
34
35
  // Send a message
35
36
  await reply.sse.send({ data: 'Hello SSE!' })
36
-
37
+
37
38
  // Send with full options
38
39
  await reply.sse.send({
39
40
  id: '123',
40
- event: 'update',
41
+ event: 'update',
41
42
  data: { message: 'Hello World' },
42
43
  retry: 1000
43
44
  })
@@ -54,7 +55,7 @@ await fastify.listen({ port: 3000 })
54
55
  await fastify.register(require('@fastify/sse'), {
55
56
  // Optional: heartbeat interval in milliseconds (default: 30000)
56
57
  heartbeatInterval: 30000,
57
-
58
+
58
59
  // Optional: default serializer (default: JSON.stringify)
59
60
  serializer: (data) => JSON.stringify(data)
60
61
  })
@@ -62,14 +63,39 @@ await fastify.register(require('@fastify/sse'), {
62
63
 
63
64
  ### Route Configuration
64
65
 
65
- ```js
66
- // Enable SSE for a route
67
- fastify.get('/events', { sse: true }, handler)
66
+ Routes opt into SSE handling by setting the `sse` field. There are three
67
+ forms, each describing what the route serves:
68
68
 
69
- // With options
70
- fastify.get('/events', {
69
+ ```js
70
+ // SSE-only route: handler always streams. Clients that explicitly refuse
71
+ // SSE (e.g. `Accept: application/json`) receive 406 Not Acceptable.
72
+ // Ambiguous Accept headers (*/*, text/*, missing) admit SSE per RFC 9110.
73
+ fastify.get('/events', { sse: 'only' }, handler)
74
+
75
+ // Dual-mode route: the same handler serves both SSE and non-SSE clients.
76
+ // Only an explicit `text/event-stream` token routes to SSE; everything
77
+ // else falls through to the handler with `reply.sse` undefined, so the
78
+ // handler is expected to produce a non-SSE response in that branch.
79
+ fastify.get('/data', { sse: 'dual' }, handler)
80
+
81
+ // Manual route: no Accept negotiation. `reply.sse` is always attached and
82
+ // the handler decides at runtime whether to stream (by calling reply.sse.*)
83
+ // or to return a normal response. Useful for streaming APIs that signal
84
+ // streaming via the request body (e.g. OpenAI-style `{ stream: true }`)
85
+ // rather than the Accept header.
86
+ fastify.post('/v1/chat', { sse: 'manual' }, handler)
87
+
88
+ // Back-compat: `sse: true` behaves like `'dual'` for routing. If the
89
+ // handler is actually SSE-only and trips a TypeError on `reply.sse`
90
+ // because of a wildcard Accept, the plugin rethrows with a message
91
+ // that names `sse: 'only'` as the fix.
92
+ fastify.get('/legacy', { sse: true }, handler)
93
+
94
+ // Object form (supports per-route options):
95
+ fastify.get('/events', {
71
96
  sse: {
72
- heartbeat: false, // Disable heartbeat for this route
97
+ kind: 'only', // 'only' | 'dual' | 'manual' — omit for back-compat
98
+ heartbeat: false, // Disable heartbeat for this route
73
99
  serializer: customSerializer // Custom serializer for this route
74
100
  }
75
101
  }, handler)
@@ -134,7 +160,7 @@ const fs = require('fs')
134
160
 
135
161
  fastify.get('/file-stream', { sse: true }, async (request, reply) => {
136
162
  const fileStream = fs.createReadStream('data.jsonl')
137
-
163
+
138
164
  // Parse each line as JSON and convert to SSE format
139
165
  const parseTransform = new Transform({
140
166
  transform(chunk, encoding, callback) {
@@ -150,7 +176,7 @@ fastify.get('/file-stream', { sse: true }, async (request, reply) => {
150
176
  callback()
151
177
  }
152
178
  })
153
-
179
+
154
180
  // Stream file data through SSE
155
181
  await pipeline(
156
182
  fileStream,
@@ -168,10 +194,13 @@ fastify.get('/file-stream', { sse: true }, async (request, reply) => {
168
194
  fastify.get('/live', { sse: true }, async (request, reply) => {
169
195
  // Keep connection alive (prevents automatic close)
170
196
  reply.sse.keepAlive()
171
-
197
+
172
198
  // Send initial message
173
199
  await reply.sse.send({ data: 'Connected' })
174
-
200
+
201
+ // Check if keepAlive was called
202
+ console.log('Keep alive status:', reply.sse.shouldKeepAlive) // true
203
+
175
204
  // Set up periodic updates
176
205
  const interval = setInterval(async () => {
177
206
  if (reply.sse.isConnected) {
@@ -180,7 +209,7 @@ fastify.get('/live', { sse: true }, async (request, reply) => {
180
209
  clearInterval(interval)
181
210
  }
182
211
  }, 1000)
183
-
212
+
184
213
  // Clean up when connection closes
185
214
  reply.sse.onClose(() => {
186
215
  clearInterval(interval)
@@ -201,16 +230,16 @@ fastify.get('/events', { sse: true }, async (request, reply) => {
201
230
  await reply.sse.replay(async (lastEventId) => {
202
231
  // Find messages after the last received ID
203
232
  const startIndex = messageHistory.findIndex(msg => msg.id === lastEventId)
204
- const messagesToReplay = startIndex !== -1
233
+ const messagesToReplay = startIndex !== -1
205
234
  ? messageHistory.slice(startIndex + 1)
206
235
  : messageHistory
207
-
236
+
208
237
  // Send missed messages
209
238
  for (const message of messagesToReplay) {
210
239
  await reply.sse.send(message)
211
240
  }
212
241
  })
213
-
242
+
214
243
  // Send new message
215
244
  const newMessage = { id: Date.now(), data: 'New event' }
216
245
  messageHistory.push(newMessage)
@@ -220,34 +249,112 @@ fastify.get('/events', { sse: true }, async (request, reply) => {
220
249
 
221
250
  ### Properties and Methods
222
251
 
223
- - `reply.sse.lastEventId`: Client's last received event ID
252
+ #### Properties
253
+
254
+ - `reply.sse.lastEventId`: Client's last received event ID (string | null)
224
255
  - `reply.sse.isConnected`: Connection status (boolean)
225
- - `reply.sse.keepAlive()`: Prevent connection from auto-closing
256
+ - `reply.sse.shouldKeepAlive`: Whether connection should be kept alive after handler completion (boolean)
257
+
258
+ #### Methods
259
+
260
+ - `reply.sse.send(source)`: Send SSE messages from various source types
261
+ - `reply.sse.stream()`: Create a transform stream for pipeline operations
262
+ - `reply.sse.keepAlive()`: Prevent connection from auto-closing after handler returns
226
263
  - `reply.sse.close()`: Manually close the connection
227
- - `reply.sse.replay(callback)`: Handle message replay
228
- - `reply.sse.onClose(callback)`: Register close callback
264
+ - `reply.sse.replay(callback)`: Handle message replay using Last-Event-ID
265
+ - `reply.sse.onClose(callback)`: Register callback for when connection closes
266
+ - `reply.sse.sendHeaders()`: Manually send headers (called automatically on first write)
229
267
 
230
268
  ## Advanced Usage
231
269
 
232
- ### Fallback to Regular Responses
233
-
234
- Routes with `{ sse: true }` automatically fall back to regular handlers when the client doesn't request SSE:
270
+ ### Accept-Header Negotiation
271
+
272
+ The plugin parses the `Accept` header per [RFC 9110 §12.5.1](https://www.rfc-editor.org/rfc/rfc9110#name-accept)
273
+ to decide whether to serve a request as SSE. The decision depends on the
274
+ route's declared kind:
275
+
276
+ | Route kind | Accept header | Behavior |
277
+ |----------------|----------------------------|-------------------------|
278
+ | `sse: 'only'` | `text/event-stream` | SSE |
279
+ | `sse: 'only'` | `*/*`, `text/*`, missing | SSE |
280
+ | `sse: 'only'` | `application/json` etc. | **406 Not Acceptable** |
281
+ | `sse: 'only'` | `…, text/event-stream;q=0` | **406 Not Acceptable** |
282
+ | `sse: 'dual'` | `text/event-stream` | SSE branch |
283
+ | `sse: 'dual'` | `*/*`, `text/*`, missing | Non-SSE branch |
284
+ | `sse: 'dual'` | `application/json` | Non-SSE branch |
285
+ | `sse: 'manual'`| (any / missing) | Handler decides at runtime |
286
+ | `sse: true` | (same routing as `'dual'`) | + explanatory error on misuse |
287
+
288
+ In short: explicit `text/event-stream` always routes to SSE; ambiguous
289
+ wildcards route to SSE only when you've declared the route SSE-only.
290
+ This keeps `curl`, `fetch()`, and Postman defaults working with SSE-only
291
+ endpoints while preserving the dual-mode pattern's expectation that a
292
+ wildcard prefers the richer non-SSE representation.
293
+
294
+ ### Fallback to Regular Responses (`sse: 'dual'`)
295
+
296
+ Dual-mode routes serve both SSE and non-SSE clients from a single
297
+ handler. The plugin attaches `reply.sse` only when the client explicitly
298
+ requested `text/event-stream`; otherwise the handler is invoked without
299
+ `reply.sse` and is expected to produce a normal response. Branch on its
300
+ presence:
235
301
 
236
302
  ```js
237
- fastify.get('/data', { sse: true }, async (request, reply) => {
303
+ fastify.get('/data', { sse: 'dual' }, async (request, reply) => {
238
304
  const data = await getData()
239
-
240
- // Check if this is an SSE request
241
- if (request.headers.accept?.includes('text/event-stream')) {
242
- // SSE client - stream the data
305
+
306
+ if (reply.sse) {
307
+ // SSE client — stream the data
243
308
  await reply.sse.send({ data })
244
309
  } else {
245
- // Regular client - return JSON
310
+ // Regular client — return JSON
246
311
  return { data }
247
312
  }
248
313
  })
249
314
  ```
250
315
 
316
+ The SSE-specific response headers (`Content-Type: text/event-stream`
317
+ etc.) are not committed until the first `reply.sse.send()` /
318
+ `reply.sse.stream()` call, so a handler that decorates `reply.sse` but
319
+ then returns a plain value falls through to Fastify's normal
320
+ serialization path without corrupting the response.
321
+
322
+ ### Dynamic Streaming Based on Request Logic (`sse: 'manual'`)
323
+
324
+ Some APIs decide whether to stream based on the request **body** rather
325
+ than the `Accept` header. OpenAI-compatible and other LLM endpoints, for
326
+ example, return a `text/event-stream` response when the request carries
327
+ `{ "stream": true }` and a single JSON object otherwise — the client
328
+ sends no `Accept: text/event-stream` header either way.
329
+
330
+ `sse: 'manual'` covers this: it skips Accept-header negotiation entirely,
331
+ always attaches `reply.sse`, and lets the handler decide at runtime
332
+ whether to stream. As with `'dual'`, SSE headers are committed lazily on
333
+ the first `reply.sse.send()` / `reply.sse.stream()` call, so a handler
334
+ that never streams falls through to Fastify's normal serialization.
335
+
336
+ ```js
337
+ fastify.post('/v1/chat/completions', { sse: 'manual' }, async (request, reply) => {
338
+ const completion = await model.run(request.body)
339
+
340
+ if (request.body.stream) {
341
+ // Stream tokens as SSE — headers commit on the first send().
342
+ await reply.sse.send(completion.tokens) // async iterable / Readable / messages
343
+ return
344
+ }
345
+
346
+ // Non-streaming client — return a normal JSON response.
347
+ return completion.toJSON()
348
+ })
349
+ ```
350
+
351
+ The connection is closed automatically when the handler resolves or
352
+ throws (call `reply.sse.keepAlive()` to keep it open for out-of-band
353
+ sends, then `reply.sse.close()` when done). Because the heartbeat only
354
+ starts once the response is committed as SSE, a non-streaming fallback
355
+ response is never corrupted by a heartbeat write.
356
+
357
+
251
358
  ### Error Handling
252
359
 
253
360
  ```js
@@ -257,11 +364,11 @@ fastify.get('/stream', { sse: true }, async (request, reply) => {
257
364
  yield { data: 'before error' }
258
365
  throw new Error('Something went wrong')
259
366
  }
260
-
367
+
261
368
  await reply.sse.send(riskyGenerator())
262
369
  } catch (error) {
263
370
  // Handle errors gracefully
264
- await reply.sse.send({
371
+ await reply.sse.send({
265
372
  event: 'error',
266
373
  data: { message: 'Stream error occurred' }
267
374
  })
@@ -318,20 +425,20 @@ assert.ok(response.body.includes('data: "Hello SSE!"'))
318
425
  </head>
319
426
  <body>
320
427
  <div id="messages"></div>
321
-
428
+
322
429
  <script>
323
430
  const eventSource = new EventSource('/events')
324
431
  const messagesDiv = document.getElementById('messages')
325
-
432
+
326
433
  eventSource.onmessage = function(event) {
327
434
  const data = JSON.parse(event.data)
328
435
  messagesDiv.innerHTML += '<div>' + JSON.stringify(data) + '</div>'
329
436
  }
330
-
437
+
331
438
  eventSource.addEventListener('update', function(event) {
332
439
  console.log('Update event:', JSON.parse(event.data))
333
440
  })
334
-
441
+
335
442
  eventSource.onerror = function(event) {
336
443
  console.error('SSE error:', event)
337
444
  }
@@ -357,12 +464,13 @@ app.get('/events', { sse: true }, async (request, reply) => {
357
464
  event: 'test',
358
465
  data: { hello: 'world' }
359
466
  }
360
-
467
+
361
468
  await reply.sse.send(message)
362
-
469
+
363
470
  // TypeScript knows about SSE properties
364
471
  console.log(reply.sse.isConnected) // boolean
365
472
  console.log(reply.sse.lastEventId) // string | null
473
+ console.log(reply.sse.shouldKeepAlive) // boolean
366
474
  })
367
475
  ```
368
476
 
@@ -371,6 +479,7 @@ app.get('/events', { sse: true }, async (request, reply) => {
371
479
  See the [examples](examples/) directory for complete working examples:
372
480
 
373
481
  - [Basic Usage](examples/basic.js) - Simple SSE endpoints
482
+ - [Dynamic Streaming](examples/manual-streaming.js) - `sse: 'manual'`, OpenAI-style stream-or-JSON based on the request body
374
483
  - More examples coming soon...
375
484
 
376
485
  ## Comparison with fastify-sse-v2
@@ -388,4 +497,4 @@ See the [examples](examples/) directory for complete working examples:
388
497
 
389
498
  ## License
390
499
 
391
- [MIT](LICENSE)
500
+ [MIT](LICENSE)