@fastify/sse 0.5.0 → 0.6.1

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.
@@ -34,6 +34,7 @@ updates:
34
34
  - dependency-name: "eslint"
35
35
  - dependency-name: "neostandard"
36
36
  - dependency-name: "@stylistic/*"
37
+ - dependency-name: "typescript"
37
38
  open-pull-requests-limit: 10
38
39
  groups:
39
40
  # Production dependencies with breaking changes
@@ -27,7 +27,7 @@ jobs:
27
27
  permissions:
28
28
  contents: write
29
29
  pull-requests: write
30
- uses: fastify/workflows/.github/workflows/plugins-ci.yml@v6
30
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@ef591e2186785d5ab36b9fe6a79c7ce2f1d94e57 # v7.0.0
31
31
  with:
32
32
  license-check: true
33
33
  lint: true
@@ -16,4 +16,4 @@ jobs:
16
16
  permissions:
17
17
  issues: write
18
18
  pull-requests: write
19
- uses: fastify/workflows/.github/workflows/lock-threads.yml@v6
19
+ uses: fastify/workflows/.github/workflows/lock-threads.yml@ef591e2186785d5ab36b9fe6a79c7ce2f1d94e57 # v7.0.0
@@ -0,0 +1,24 @@
1
+ name: Release the package
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ semver:
7
+ description: 'Release bump type'
8
+ required: true
9
+ type: choice
10
+ options:
11
+ - patch
12
+ - minor
13
+ - major
14
+
15
+ permissions: {}
16
+
17
+ jobs:
18
+ release:
19
+ permissions:
20
+ id-token: write # required for npm provenance via OIDC
21
+ contents: write # required to push the release commit and the tag
22
+ uses: fastify/workflows/.github/workflows/reusable-release.yml@b1a11bce713bc857e52b2231fec3c89071ad3135
23
+ with:
24
+ semver: ${{ inputs.semver }}
package/README.md CHANGED
@@ -263,13 +263,35 @@ fastify.get('/events', { sse: true }, async (request, reply) => {
263
263
  - `reply.sse.close()`: Manually close the connection
264
264
  - `reply.sse.replay(callback)`: Handle message replay using Last-Event-ID
265
265
  - `reply.sse.onClose(callback)`: Register callback for when connection closes
266
- - `reply.sse.sendHeaders()`: Manually send headers (called automatically on first write)
266
+ - `reply.sse.sendHeaders(statusCode?)`: Manually send headers (called automatically on first write)
267
+
268
+ ### Custom Response Status Code
269
+
270
+ The SSE response defaults to `200 OK`. To use a different status, either call
271
+ `reply.code()` before the first SSE write, or pass the status directly to a
272
+ manual `reply.sse.sendHeaders()` call:
273
+
274
+ ```javascript
275
+ fastify.get('/events', { sse: 'only' }, async (request, reply) => {
276
+ reply.code(201)
277
+ await reply.sse.send({ data: 'created' })
278
+ })
279
+
280
+ fastify.get('/events-explicit', { sse: 'only' }, async (request, reply) => {
281
+ reply.sse.sendHeaders(201)
282
+ await reply.sse.send({ data: 'created' })
283
+ })
284
+ ```
285
+
286
+ An explicit `sendHeaders()` argument takes precedence over `reply.code()`.
287
+ Once the first SSE write commits the response headers, later `reply.code()`
288
+ or `sendHeaders()` calls have no effect.
267
289
 
268
290
  ## Advanced Usage
269
291
 
270
292
  ### Accept-Header Negotiation
271
293
 
272
- The plugin parses the `Accept` header per [RFC 9110 §12.5.1](https://www.rfc-editor.org/rfc/rfc9110#name-accept)
294
+ The plugin parses the `Accept` header per [RFC 9110 §12.5.1](https://www.rfc-editor.org/rfc/rfc9110.html#name-accept)
273
295
  to decide whether to serve a request as SSE. The decision depends on the
274
296
  route's declared kind:
275
297
 
package/index.js CHANGED
@@ -416,14 +416,19 @@ class SSEContext {
416
416
  /**
417
417
  * Sends HTTP headers for the SSE response if not already sent.
418
418
  * Applies the SSE-specific response headers, transfers any headers set
419
- * via reply.header(), and calls writeHead(200). Called automatically
420
- * before the first SSE data is sent, but can also be called manually.
419
+ * via reply.header(), and writes the response head. The status code is
420
+ * resolved in order: the explicit `statusCode` argument, then the value
421
+ * set via reply.code(), then 200. The automatic call before the first
422
+ * SSE write passes no argument, so an explicit status only takes effect
423
+ * on manual calls made before any data is sent.
421
424
  *
422
425
  * Until this fires, the response is not yet committed as SSE — a handler
423
426
  * that never writes SSE data will return through Fastify's normal
424
427
  * serialization path.
428
+ *
429
+ * @param {number} [statusCode] - HTTP status for the SSE response.
425
430
  */
426
- sendHeaders () {
431
+ sendHeaders (statusCode) {
427
432
  if (!this.#headersSent) {
428
433
  this.reply.raw.setHeader('Content-Type', 'text/event-stream')
429
434
  this.reply.raw.setHeader('Cache-Control', 'no-cache')
@@ -436,7 +441,10 @@ class SSEContext {
436
441
  this.reply.raw.setHeader(name, value)
437
442
  }
438
443
 
439
- this.reply.raw.writeHead(200)
444
+ // Status precedence: explicit sendHeaders() argument, then the value
445
+ // the handler set via reply.code() (stored on raw.statusCode), then
446
+ // 200 as the final fallback.
447
+ this.reply.raw.writeHead(statusCode ?? this.reply.raw.statusCode ?? 200)
440
448
  this.#headersSent = true
441
449
 
442
450
  // Start the heartbeat only once the response is committed as SSE.
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@fastify/sse",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Server-Sent Events plugin for Fastify",
5
5
  "main": "index.js",
6
6
  "types": "types/index.d.ts",
7
7
  "scripts": {
8
8
  "test": "npm run test:unit && npm run test:typescript && npm run test:attw",
9
- "test:unit": "node --test",
9
+ "test:unit": "c8 --100 node --test",
10
10
  "test:typescript": "tstyche",
11
11
  "test:attw": "attw --pack .",
12
12
  "lint": "eslint .",
@@ -39,6 +39,7 @@
39
39
  "devDependencies": {
40
40
  "@arethetypeswrong/cli": "^0.18.2",
41
41
  "@types/node": "^26.0.0",
42
+ "c8": "^12.0.0",
42
43
  "eslint": "^9.0.0",
43
44
  "fastify": "^5.0.0",
44
45
  "neostandard": "^0.13.0",
@@ -0,0 +1,85 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const { strict: assert } = require('node:assert')
5
+ const Fastify = require('fastify')
6
+ const fastifySSE = require('../index.js')
7
+
8
+ async function buildApp (t, options = {}) {
9
+ const app = Fastify({ logger: false })
10
+
11
+ t.after(async () => {
12
+ await app.close()
13
+ })
14
+
15
+ await app.register(fastifySSE, options)
16
+ return app
17
+ }
18
+
19
+ test('waits for drain when the response applies backpressure', async (t) => {
20
+ const app = await buildApp(t, { heartbeatInterval: 0 })
21
+ let errorListenersBefore
22
+ let errorListenersAfter
23
+
24
+ app.get('/events', { sse: true }, async (request, reply) => {
25
+ const raw = reply.raw
26
+ const originalWrite = raw.write
27
+ errorListenersBefore = raw.listenerCount('error')
28
+
29
+ raw.write = function (...args) {
30
+ originalWrite.apply(this, args)
31
+ setImmediate(() => raw.emit('drain'))
32
+ return false
33
+ }
34
+
35
+ await reply.sse.send({ data: 'backpressure' })
36
+ raw.write = originalWrite
37
+ errorListenersAfter = raw.listenerCount('error')
38
+ })
39
+
40
+ const response = await app.inject({
41
+ url: '/events',
42
+ headers: { accept: 'text/event-stream' }
43
+ })
44
+
45
+ assert.match(response.body, /data: "backpressure"/)
46
+ assert.strictEqual(errorListenersAfter, errorListenersBefore)
47
+ })
48
+
49
+ test('handles a response error while waiting for drain', async (t) => {
50
+ const app = await buildApp(t, { heartbeatInterval: 0 })
51
+ const infoLog = t.mock.fn()
52
+ let context
53
+
54
+ app.get('/events', { sse: true }, async (request, reply) => {
55
+ context = reply.sse
56
+ reply.log.info = infoLog
57
+
58
+ const raw = reply.raw
59
+ const originalWrite = raw.write
60
+ raw.write = function (...args) {
61
+ originalWrite.apply(this, args)
62
+ setImmediate(() => raw.emit('error', new Error('write failed')))
63
+ return false
64
+ }
65
+
66
+ await reply.sse.send({ data: 'backpressure' })
67
+ raw.write = originalWrite
68
+ raw.end()
69
+ })
70
+
71
+ await assert.rejects(
72
+ () => app.inject({
73
+ url: '/events',
74
+ headers: { accept: 'text/event-stream' }
75
+ }),
76
+ { message: 'write failed' }
77
+ )
78
+
79
+ const messages = infoLog.mock.calls.map((call) => call.arguments[1])
80
+ assert.deepStrictEqual(messages, [
81
+ 'SSE connection closed',
82
+ 'SSE write ended'
83
+ ])
84
+ assert.strictEqual(context.isConnected, false)
85
+ })
@@ -557,3 +557,130 @@ test('unknown sse kind throws at registration', async (t) => {
557
557
  /unknown sse kind 'maybe'/
558
558
  )
559
559
  })
560
+
561
+ async function buildApp (t, options = {}) {
562
+ const app = Fastify({ logger: false })
563
+
564
+ t.after(async () => {
565
+ await app.close()
566
+ })
567
+
568
+ await app.register(fastifySSE, options)
569
+ return app
570
+ }
571
+
572
+ test('formats multiline Buffer messages', async (t) => {
573
+ const app = await buildApp(t, { heartbeatInterval: 0 })
574
+
575
+ app.get('/events', { sse: true }, async (request, reply) => {
576
+ await reply.sse.send(Buffer.from('first\nsecond'))
577
+ })
578
+
579
+ const response = await app.inject({
580
+ url: '/events',
581
+ headers: { accept: 'text/event-stream' }
582
+ })
583
+
584
+ assert.strictEqual(response.body, 'data: first\ndata: second\n\n')
585
+ })
586
+
587
+ test('leaves ordinary routes alone and falls back when Accept is missing', async (t) => {
588
+ const app = await buildApp(t, { heartbeatInterval: 0 })
589
+
590
+ app.get('/plain', async () => ({ plain: true }))
591
+ app.get('/events', { sse: true }, async (request, reply) => {
592
+ return { fallback: reply.sse === undefined }
593
+ })
594
+
595
+ const plainResponse = await app.inject({ url: '/plain' })
596
+ const fallbackResponse = await app.inject({ url: '/events' })
597
+
598
+ assert.deepStrictEqual(plainResponse.json(), { plain: true })
599
+ assert.deepStrictEqual(fallbackResponse.json(), { fallback: true })
600
+ })
601
+
602
+ test('parses SSE Accept parameters and optional whitespace', async (t) => {
603
+ const app = await buildApp(t, { heartbeatInterval: 0 })
604
+
605
+ app.get('/events', { sse: 'only' }, async (request, reply) => {
606
+ await reply.sse.send({ data: 'accepted' })
607
+ })
608
+
609
+ const cases = [
610
+ ['TEXT/EVENT-STREAM', 200],
611
+ ['text/event-streax', 406],
612
+ ['text/event-stream;q=', 200],
613
+ ['text/event-stream;q=1', 200],
614
+ ['text/event-stream;q=0.00', 406],
615
+ ['text/event-stream;q=0.01', 200],
616
+ ['text/event-stream ;q=0', 406],
617
+ ['text/*;q=0', 406],
618
+ ['application/json;foo=bar, text/event-stream', 200],
619
+ ['text/event-stream; q=0', 406],
620
+ ['text/event-stream;q=0;foo=bar', 406],
621
+ ['text/event-stream;Q=0', 406]
622
+ ]
623
+
624
+ for (const [accept, expectedStatus] of cases) {
625
+ const response = await app.inject({
626
+ url: '/events',
627
+ headers: { accept }
628
+ })
629
+
630
+ assert.strictEqual(response.statusCode, expectedStatus, accept)
631
+ }
632
+ })
633
+
634
+ test('rejects unsupported route option values', async (t) => {
635
+ const app = await buildApp(t, { heartbeatInterval: 0 })
636
+
637
+ assert.throws(
638
+ () => app.get('/invalid', { sse: 42 }, async () => {}),
639
+ /unsupported value for route option 'sse': 42/
640
+ )
641
+ })
642
+
643
+ test('preserves legacy fallback errors and describes missing Accept misuse', async (t) => {
644
+ const app = await buildApp(t, { heartbeatInterval: 0 })
645
+
646
+ app.get('/misuse', { sse: true }, async (request, reply) => {
647
+ await reply.sse.send({ data: 'value' })
648
+ })
649
+
650
+ app.get('/failure', { sse: true }, async () => {
651
+ throw new Error('fallback failed')
652
+ })
653
+
654
+ const misuseResponse = await app.inject({ url: '/misuse' })
655
+ const failureResponse = await app.inject({ url: '/failure' })
656
+
657
+ assert.strictEqual(misuseResponse.statusCode, 500)
658
+ assert.match(misuseResponse.body, /<missing>/)
659
+ assert.strictEqual(failureResponse.statusCode, 500)
660
+ assert.match(failureResponse.body, /fallback failed/)
661
+ })
662
+
663
+ test('supports route-level serializer and disabled heartbeat options', async (t) => {
664
+ const app = await buildApp(t, { heartbeatInterval: 1 })
665
+ let context
666
+
667
+ app.get('/events', {
668
+ sse: {
669
+ heartbeat: false,
670
+ serializer: (data) => `route:${data}`
671
+ }
672
+ }, async (request, reply) => {
673
+ context = reply.sse
674
+ reply.sse.keepAlive()
675
+ await reply.sse.send({ data: 'value' })
676
+ setTimeout(() => reply.sse.close(), 20)
677
+ })
678
+
679
+ const response = await app.inject({
680
+ url: '/events',
681
+ headers: { accept: 'text/event-stream' }
682
+ })
683
+
684
+ assert.strictEqual(response.body, 'data: route:value\n\n')
685
+ assert.strictEqual(context.heartbeatTimer, null)
686
+ })
@@ -4,6 +4,7 @@ const { test } = require('node:test')
4
4
  const { strict: assert } = require('node:assert')
5
5
  const Fastify = require('fastify')
6
6
  const fastifySSE = require('../index.js')
7
+ const { setTimeout: sleep } = require('node:timers/promises')
7
8
 
8
9
  test('Last-Event-ID header parsing', async (t) => {
9
10
  const fastify = Fastify({ logger: false })
@@ -185,3 +186,198 @@ test('error handling in async iterator', async (t) => {
185
186
  assert.ok(body.includes('data: "before error"'))
186
187
  assert.ok(body.includes('data: "error handled"'))
187
188
  })
189
+
190
+ async function buildApp (t, options = {}) {
191
+ const app = Fastify({ logger: false })
192
+
193
+ t.after(async () => {
194
+ await app.close()
195
+ })
196
+
197
+ await app.register(fastifySSE, options)
198
+ return app
199
+ }
200
+
201
+ test('handles replay without an event ID and rejects invalid sources', async (t) => {
202
+ const app = await buildApp(t, { heartbeatInterval: 0 })
203
+ let replayCalls = 0
204
+
205
+ app.get('/events', { sse: true }, async (request, reply) => {
206
+ await reply.sse.replay(async () => {
207
+ replayCalls++
208
+ })
209
+
210
+ for (const source of [null, 42, {}]) {
211
+ await assert.rejects(
212
+ () => reply.sse.send(source),
213
+ { name: 'TypeError', message: 'Invalid SSE source type' }
214
+ )
215
+ }
216
+
217
+ await reply.sse.send({ data: 'valid' })
218
+ })
219
+
220
+ const response = await app.inject({
221
+ url: '/events',
222
+ headers: { accept: 'text/event-stream' }
223
+ })
224
+
225
+ assert.strictEqual(replayCalls, 0)
226
+ assert.match(response.body, /data: "valid"/)
227
+ })
228
+
229
+ test('closed contexts reject writes and stop restarted heartbeats', async (t) => {
230
+ const app = await buildApp(t, { heartbeatInterval: 0 })
231
+ let context
232
+
233
+ app.get('/events', { sse: true }, async (request, reply) => {
234
+ context = reply.sse
235
+ reply.sse.close()
236
+ reply.sse.close()
237
+
238
+ assert.throws(
239
+ () => reply.sse.stream(),
240
+ { message: 'SSE connection is closed' }
241
+ )
242
+ await assert.rejects(
243
+ () => reply.sse.send({ data: 'late' }),
244
+ { message: 'SSE connection is closed' }
245
+ )
246
+ })
247
+
248
+ const response = await app.inject({
249
+ url: '/events',
250
+ headers: { accept: 'text/event-stream' }
251
+ })
252
+
253
+ assert.strictEqual(response.statusCode, 200)
254
+ assert.strictEqual(context.isConnected, false)
255
+
256
+ context.startHeartbeat(1)
257
+ await sleep(20)
258
+ assert.strictEqual(context.heartbeatTimer, null)
259
+ })
260
+
261
+ test('detects a connection closed synchronously by the serializer', async (t) => {
262
+ let context
263
+ const app = await buildApp(t, {
264
+ heartbeatInterval: 0,
265
+ serializer (data) {
266
+ context.close()
267
+ return JSON.stringify(data)
268
+ }
269
+ })
270
+
271
+ app.get('/events', { sse: true }, async (request, reply) => {
272
+ context = reply.sse
273
+ await assert.rejects(
274
+ () => reply.sse.send({ data: 'value' }),
275
+ { message: 'SSE connection is closed' }
276
+ )
277
+ })
278
+
279
+ const response = await app.inject({
280
+ url: '/events',
281
+ headers: { accept: 'text/event-stream' }
282
+ })
283
+
284
+ assert.strictEqual(response.statusCode, 200)
285
+ assert.strictEqual(context.isConnected, false)
286
+ })
287
+
288
+ test('stops an async iterable when the connection closes', async (t) => {
289
+ const app = await buildApp(t, { heartbeatInterval: 0 })
290
+
291
+ app.get('/events', { sse: true }, async (request, reply) => {
292
+ async function * events () {
293
+ yield { data: 'first' }
294
+ reply.sse.close()
295
+ yield { data: 'second' }
296
+ }
297
+
298
+ await reply.sse.send(events())
299
+ })
300
+
301
+ const response = await app.inject({
302
+ url: '/events',
303
+ headers: { accept: 'text/event-stream' }
304
+ })
305
+
306
+ assert.match(response.body, /data: "first"/)
307
+ assert.doesNotMatch(response.body, /second/)
308
+ })
309
+
310
+ test('emits heartbeats and clears the timer when closed', async (t) => {
311
+ const app = await buildApp(t, { heartbeatInterval: 5 })
312
+ let context
313
+
314
+ app.get('/events', { sse: true }, async (request, reply) => {
315
+ context = reply.sse
316
+ reply.sse.sendHeaders()
317
+ reply.sse.keepAlive()
318
+ setTimeout(() => reply.sse.close(), 40)
319
+ })
320
+
321
+ const response = await app.inject({
322
+ url: '/events',
323
+ headers: { accept: 'text/event-stream' }
324
+ })
325
+
326
+ assert.match(response.body, /: heartbeat\n\n/)
327
+ assert.strictEqual(context.heartbeatTimer, null)
328
+ })
329
+
330
+ test('logs close callback failures without preventing cleanup', async (t) => {
331
+ const app = await buildApp(t, { heartbeatInterval: 0 })
332
+ const consoleError = t.mock.method(console, 'error', () => {})
333
+ let context
334
+
335
+ app.get('/events', { sse: true }, async (request, reply) => {
336
+ context = reply.sse
337
+ reply.sse.onClose(() => {
338
+ throw new Error('close callback failed')
339
+ })
340
+ await reply.sse.send({ data: 'value' })
341
+ })
342
+
343
+ await app.inject({
344
+ url: '/events',
345
+ headers: { accept: 'text/event-stream' }
346
+ })
347
+
348
+ assert.strictEqual(consoleError.mock.callCount(), 1)
349
+ assert.strictEqual(context.closeCallbacks.length, 0)
350
+ })
351
+
352
+ test('cleans up when handlers fail with and without keepAlive', async (t) => {
353
+ const app = await buildApp(t, { heartbeatInterval: 0 })
354
+ let closedContext
355
+ let keptContext
356
+
357
+ app.get('/closed', { sse: true }, async (request, reply) => {
358
+ closedContext = reply.sse
359
+ throw new Error('closed handler failed')
360
+ })
361
+
362
+ app.get('/kept', { sse: true }, async (request, reply) => {
363
+ keptContext = reply.sse
364
+ reply.sse.keepAlive()
365
+ throw new Error('kept handler failed')
366
+ })
367
+
368
+ const closedResponse = await app.inject({
369
+ url: '/closed',
370
+ headers: { accept: 'text/event-stream' }
371
+ })
372
+ const keptResponse = await app.inject({
373
+ url: '/kept',
374
+ headers: { accept: 'text/event-stream' }
375
+ })
376
+
377
+ assert.strictEqual(closedResponse.statusCode, 500)
378
+ assert.match(closedResponse.body, /closed handler failed/)
379
+ assert.strictEqual(closedContext.isConnected, false)
380
+ assert.strictEqual(keptResponse.statusCode, 500)
381
+ assert.match(keptResponse.body, /kept handler failed/)
382
+ assert.strictEqual(keptContext.isConnected, false)
383
+ })