@fastify/sse 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -168,10 +168,13 @@ fastify.get('/file-stream', { sse: true }, async (request, reply) => {
168
168
  fastify.get('/live', { sse: true }, async (request, reply) => {
169
169
  // Keep connection alive (prevents automatic close)
170
170
  reply.sse.keepAlive()
171
-
171
+
172
172
  // Send initial message
173
173
  await reply.sse.send({ data: 'Connected' })
174
-
174
+
175
+ // Check if keepAlive was called
176
+ console.log('Keep alive status:', reply.sse.shouldKeepAlive) // true
177
+
175
178
  // Set up periodic updates
176
179
  const interval = setInterval(async () => {
177
180
  if (reply.sse.isConnected) {
@@ -180,7 +183,7 @@ fastify.get('/live', { sse: true }, async (request, reply) => {
180
183
  clearInterval(interval)
181
184
  }
182
185
  }, 1000)
183
-
186
+
184
187
  // Clean up when connection closes
185
188
  reply.sse.onClose(() => {
186
189
  clearInterval(interval)
@@ -220,12 +223,19 @@ fastify.get('/events', { sse: true }, async (request, reply) => {
220
223
 
221
224
  ### Properties and Methods
222
225
 
223
- - `reply.sse.lastEventId`: Client's last received event ID
226
+ #### Properties
227
+ - `reply.sse.lastEventId`: Client's last received event ID (string | null)
224
228
  - `reply.sse.isConnected`: Connection status (boolean)
225
- - `reply.sse.keepAlive()`: Prevent connection from auto-closing
229
+ - `reply.sse.shouldKeepAlive`: Whether connection should be kept alive after handler completion (boolean)
230
+
231
+ #### Methods
232
+ - `reply.sse.send(source)`: Send SSE messages from various source types
233
+ - `reply.sse.stream()`: Create a transform stream for pipeline operations
234
+ - `reply.sse.keepAlive()`: Prevent connection from auto-closing after handler returns
226
235
  - `reply.sse.close()`: Manually close the connection
227
- - `reply.sse.replay(callback)`: Handle message replay
228
- - `reply.sse.onClose(callback)`: Register close callback
236
+ - `reply.sse.replay(callback)`: Handle message replay using Last-Event-ID
237
+ - `reply.sse.onClose(callback)`: Register callback for when connection closes
238
+ - `reply.sse.sendHeaders()`: Manually send headers (called automatically on first write)
229
239
 
230
240
  ## Advanced Usage
231
241
 
@@ -357,12 +367,13 @@ app.get('/events', { sse: true }, async (request, reply) => {
357
367
  event: 'test',
358
368
  data: { hello: 'world' }
359
369
  }
360
-
370
+
361
371
  await reply.sse.send(message)
362
-
372
+
363
373
  // TypeScript knows about SSE properties
364
374
  console.log(reply.sse.isConnected) // boolean
365
375
  console.log(reply.sse.lastEventId) // string | null
376
+ console.log(reply.sse.shouldKeepAlive) // boolean
366
377
  })
367
378
  ```
368
379
 
package/examples/basic.js CHANGED
@@ -69,6 +69,26 @@ fastify.get('/live', { sse: true }, async (request, reply) => {
69
69
  })
70
70
  })
71
71
 
72
+ // Custom headers with sendHeaders
73
+ fastify.get('/headers', { sse: true }, async (request, reply) => {
74
+ // Set custom headers using Fastify's header methods
75
+ reply.header('X-Session-ID', 'session-12345')
76
+ reply.header('X-API-Version', 'v1.2.3')
77
+ reply.headers({
78
+ 'X-User-Agent': request.headers['user-agent'] || 'unknown',
79
+ 'X-Request-Time': new Date().toISOString()
80
+ })
81
+
82
+ // Manually send headers before any SSE data
83
+ reply.sse.sendHeaders()
84
+
85
+ // Now send SSE data
86
+ await reply.sse.send({
87
+ data: 'Headers sent manually before this message',
88
+ event: 'custom-headers'
89
+ })
90
+ })
91
+
72
92
  // Replay functionality
73
93
  const messageHistory = []
74
94
  let eventId = 0
@@ -111,6 +131,7 @@ const start = async () => {
111
131
  console.log(' GET /events - Basic SSE messages')
112
132
  console.log(' GET /stream - Streaming with async generator')
113
133
  console.log(' GET /live - Persistent connection with heartbeat')
134
+ console.log(' GET /headers - Custom headers with sendHeaders()')
114
135
  console.log(' GET /replay - Messages with replay support')
115
136
  } catch (err) {
116
137
  fastify.log.error(err)
package/index.js CHANGED
@@ -4,9 +4,6 @@ const fp = require('fastify-plugin')
4
4
  const { Readable, Transform } = require('stream')
5
5
  const { pipeline } = require('stream/promises')
6
6
 
7
- const SSE_DECORATOR = Symbol.for('@fastify/sse.decorator')
8
- const SSE_CONTEXT = Symbol.for('@fastify/sse.context')
9
-
10
7
  /**
11
8
  * Format an SSE message according to the specification
12
9
  * @param {Object|string|Buffer} message - The message to format
@@ -84,26 +81,31 @@ function createSSETransformStream (options = {}) {
84
81
  * SSE Context class for managing connection state
85
82
  */
86
83
  class SSEContext {
84
+ #lastEventId
85
+ #isConnected
86
+ #keepAlive
87
+ #headersSent
88
+
87
89
  constructor (options) {
88
90
  this.reply = options.reply
89
- this._lastEventId = options.lastEventId || null
90
- this._isConnected = true
91
- this._keepAlive = false
92
- this._headersSent = false
91
+ this.#lastEventId = options.lastEventId || null
92
+ this.#isConnected = true
93
+ this.#keepAlive = false
94
+ this.#headersSent = false
93
95
  this.heartbeatTimer = null
94
96
  this.closeCallbacks = []
95
97
  this.serializer = options.serializer
96
98
 
97
99
  // Set up connection close handler
98
100
  this.reply.raw.on('close', () => {
99
- this._isConnected = false
101
+ this.#isConnected = false
100
102
  this.cleanup()
101
103
  })
102
104
 
103
105
  // Handle errors on the raw response to prevent uncaught exceptions
104
106
  this.reply.raw.on('error', (error) => {
105
107
  // Client disconnection is expected behavior, handle gracefully
106
- this._isConnected = false
108
+ this.#isConnected = false
107
109
  this.cleanup()
108
110
  // Log as info since client disconnections are normal
109
111
  this.reply.log.info({ err: error }, 'SSE connection closed')
@@ -120,7 +122,7 @@ class SSEContext {
120
122
  * @returns {string|null} The last event ID or null if not present
121
123
  */
122
124
  get lastEventId () {
123
- return this._lastEventId
125
+ return this.#lastEventId
124
126
  }
125
127
 
126
128
  /**
@@ -128,7 +130,15 @@ class SSEContext {
128
130
  * @returns {boolean} True if connected, false otherwise
129
131
  */
130
132
  get isConnected () {
131
- return this._isConnected
133
+ return this.#isConnected
134
+ }
135
+
136
+ /**
137
+ * Checks if the connection should be kept alive after handler completion.
138
+ * @returns {boolean} True if connection should be kept alive
139
+ */
140
+ get shouldKeepAlive () {
141
+ return this.#keepAlive
132
142
  }
133
143
 
134
144
  /**
@@ -136,7 +146,7 @@ class SSEContext {
136
146
  * Without calling this, the connection will close after the handler returns.
137
147
  */
138
148
  keepAlive () {
139
- this._keepAlive = true
149
+ this.#keepAlive = true
140
150
  }
141
151
 
142
152
  /**
@@ -144,9 +154,9 @@ class SSEContext {
144
154
  * Safe to call multiple times.
145
155
  */
146
156
  close () {
147
- if (!this._isConnected) return
157
+ if (!this.#isConnected) return
148
158
 
149
- this._isConnected = false
159
+ this.#isConnected = false
150
160
  this.cleanup()
151
161
  this.reply.raw.end()
152
162
  }
@@ -165,20 +175,20 @@ class SSEContext {
165
175
  * @param {Function} callback - Async function that receives the last event ID
166
176
  */
167
177
  async replay (callback) {
168
- if (!this._lastEventId) return
178
+ if (!this.#lastEventId) return
169
179
 
170
- await callback(this._lastEventId)
180
+ await callback(this.#lastEventId)
171
181
  }
172
182
 
173
183
  /**
174
184
  * Sends HTTP headers for the SSE response if not already sent.
175
185
  * This method ensures headers set via reply.header() are transferred
176
186
  * to the raw response before calling writeHead(200).
177
- * Called automatically before the first SSE data is sent.
178
- * @private
187
+ * Called automatically before the first SSE data is sent, but can
188
+ * also be called manually if needed.
179
189
  */
180
190
  sendHeaders () {
181
- if (!this._headersSent) {
191
+ if (!this.#headersSent) {
182
192
  // Get any headers set via reply.header() and transfer to raw response
183
193
  const replyHeaders = this.reply.getHeaders()
184
194
  for (const [name, value] of Object.entries(replyHeaders)) {
@@ -186,7 +196,7 @@ class SSEContext {
186
196
  }
187
197
 
188
198
  this.reply.raw.writeHead(200)
189
- this._headersSent = true
199
+ this.#headersSent = true
190
200
  }
191
201
  }
192
202
 
@@ -197,7 +207,7 @@ class SSEContext {
197
207
  * @throws {TypeError} If source type is invalid
198
208
  */
199
209
  async send (source) {
200
- if (!this._isConnected) {
210
+ if (!this.#isConnected) {
201
211
  throw new Error('SSE connection is closed')
202
212
  }
203
213
 
@@ -217,7 +227,7 @@ class SSEContext {
217
227
  await pipeline(source, transform, this.reply.raw, { end: false })
218
228
  } catch (error) {
219
229
  // Distinguish between expected disconnection errors and unexpected errors
220
- this._isConnected = false
230
+ this.#isConnected = false
221
231
  this.cleanup()
222
232
  if (error && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
223
233
  this.reply.log.info({ err: error }, 'SSE stream ended (client disconnected)')
@@ -232,7 +242,7 @@ class SSEContext {
232
242
  // Handle AsyncIterable
233
243
  if (this.isAsyncIterable(source)) {
234
244
  for await (const chunk of source) {
235
- if (!this._isConnected) break
245
+ if (!this.#isConnected) break
236
246
  const formatted = formatSSEMessage(chunk, this.serializer)
237
247
  await this.writeToStream(formatted)
238
248
  }
@@ -249,7 +259,7 @@ class SSEContext {
249
259
  * @throws {Error} If connection is closed
250
260
  */
251
261
  stream () {
252
- if (!this._isConnected) {
262
+ if (!this.#isConnected) {
253
263
  throw new Error('SSE connection is closed')
254
264
  }
255
265
 
@@ -273,7 +283,7 @@ class SSEContext {
273
283
  */
274
284
  writeToStream (data) {
275
285
  return new Promise((resolve, reject) => {
276
- if (!this._isConnected) {
286
+ if (!this.#isConnected) {
277
287
  reject(new Error('SSE connection is closed'))
278
288
  return
279
289
  }
@@ -295,7 +305,7 @@ class SSEContext {
295
305
  const onError = (err) => {
296
306
  this.reply.raw.off('drain', onDrain)
297
307
  // Handle all errors gracefully - client disconnection is normal
298
- this._isConnected = false
308
+ this.#isConnected = false
299
309
  this.cleanup()
300
310
  this.reply.log.info({ err }, 'SSE write ended')
301
311
  resolve() // Resolve instead of reject for graceful handling
@@ -314,7 +324,7 @@ class SSEContext {
314
324
  */
315
325
  startHeartbeat (interval) {
316
326
  this.heartbeatTimer = setInterval(() => {
317
- if (this._isConnected) {
327
+ if (this.#isConnected) {
318
328
  this.sendHeaders()
319
329
  this.reply.raw.write(': heartbeat\n\n')
320
330
  } else {
@@ -418,48 +428,27 @@ async function fastifySSE (fastify, opts) {
418
428
  })
419
429
 
420
430
  // Store context on reply
421
- reply[SSE_CONTEXT] = context
422
-
423
- // Decorate reply with SSE interface
424
- const sseInterface = {}
425
-
426
- // Add SSE methods
427
- Object.defineProperty(sseInterface, 'lastEventId', {
428
- get: () => context.lastEventId
429
- })
430
-
431
- sseInterface.send = (source) => context.send(source)
432
- sseInterface.stream = () => context.stream()
433
- sseInterface.keepAlive = () => context.keepAlive()
434
- sseInterface.close = () => context.close()
435
- sseInterface.replay = (callback) => context.replay(callback)
436
- sseInterface.onClose = (callback) => context.onClose(callback)
437
-
438
- Object.defineProperty(sseInterface, 'isConnected', {
439
- get: () => context.isConnected
440
- })
441
-
442
- reply[SSE_DECORATOR] = sseInterface
443
- Object.defineProperty(reply, 'sse', {
444
- get () { return this[SSE_DECORATOR] }
445
- })
431
+ reply.sse = context
446
432
 
433
+ let res
447
434
  // Call original handler with SSE-enabled reply
448
435
  // Note: Headers will be sent on first SSE send
449
436
  try {
450
- await originalHandler.call(this, request, reply)
437
+ res = await originalHandler.call(this, request, reply)
451
438
  } catch (error) {
452
439
  // If handler doesn't call keepAlive, close connection
453
- if (!reply[SSE_CONTEXT]?._keepAlive) {
454
- reply[SSE_CONTEXT]?.close()
440
+ if (!context.shouldKeepAlive) {
441
+ context.close()
455
442
  }
456
443
  throw error
457
444
  }
458
445
 
459
446
  // If handler doesn't call keepAlive, close connection
460
- if (!reply[SSE_CONTEXT]?._keepAlive) {
461
- reply[SSE_CONTEXT]?.close()
447
+ if (!context.shouldKeepAlive) {
448
+ context.close()
462
449
  }
450
+
451
+ return res
463
452
  }
464
453
  })
465
454
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/sse",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Server-Sent Events plugin for Fastify",
5
5
  "main": "index.js",
6
6
  "types": "types/index.d.ts",
@@ -19,8 +19,6 @@ test('basic SSE functionality', async (t) => {
19
19
  await reply.sse.send({ data: 'hello world' })
20
20
  })
21
21
 
22
- await fastify.listen({ port: 0 })
23
-
24
22
  const response = await fastify.inject({
25
23
  method: 'GET',
26
24
  url: '/events',
@@ -57,8 +55,6 @@ test('SSE message formatting', async (t) => {
57
55
  })
58
56
  })
59
57
 
60
- await fastify.listen({ port: 0 })
61
-
62
58
  const response = await fastify.inject({
63
59
  method: 'GET',
64
60
  url: '/events',
@@ -87,8 +83,6 @@ test('string message support', async (t) => {
87
83
  await reply.sse.send('plain text message')
88
84
  })
89
85
 
90
- await fastify.listen({ port: 0 })
91
-
92
86
  const response = await fastify.inject({
93
87
  method: 'GET',
94
88
  url: '/events',
@@ -114,8 +108,6 @@ test('multiline data handling', async (t) => {
114
108
  await reply.sse.send({ data: 'line1\nline2\nline3' })
115
109
  })
116
110
 
117
- await fastify.listen({ port: 0 })
118
-
119
111
  const response = await fastify.inject({
120
112
  method: 'GET',
121
113
  url: '/events',
@@ -147,8 +139,6 @@ test('async generator support', async (t) => {
147
139
  await reply.sse.send(generate())
148
140
  })
149
141
 
150
- await fastify.listen({ port: 0 })
151
-
152
142
  const response = await fastify.inject({
153
143
  method: 'GET',
154
144
  url: '/stream',
@@ -185,8 +175,6 @@ test('readable stream support', async (t) => {
185
175
  await reply.sse.send(stream)
186
176
  })
187
177
 
188
- await fastify.listen({ port: 0 })
189
-
190
178
  const response = await fastify.inject({
191
179
  method: 'GET',
192
180
  url: '/stream',
@@ -254,8 +242,6 @@ test('custom serializer', async (t) => {
254
242
  await reply.sse.send({ data: 'test' })
255
243
  })
256
244
 
257
- await fastify.listen({ port: 0 })
258
-
259
245
  const response = await fastify.inject({
260
246
  method: 'GET',
261
247
  url: '/events',
@@ -291,8 +277,6 @@ test('reply.sse.stream() for pipeline operations', async (t) => {
291
277
  await pipeline(sourceStream, reply.sse.stream(), reply.raw, { end: false })
292
278
  })
293
279
 
294
- await fastify.listen({ port: 0 })
295
-
296
280
  const response = await fastify.inject({
297
281
  method: 'GET',
298
282
  url: '/pipeline',
@@ -23,8 +23,6 @@ test('should allow setting custom headers in SSE responses', async (t) => {
23
23
  await reply.sse.send({ data: 'hello' })
24
24
  })
25
25
 
26
- await fastify.listen({ port: 0 })
27
-
28
26
  const response = await fastify.inject({
29
27
  method: 'GET',
30
28
  url: '/events',
@@ -62,8 +60,6 @@ test('should allow setting headers via reply.header() method', async (t) => {
62
60
  await reply.sse.send({ data: 'test' })
63
61
  })
64
62
 
65
- await fastify.listen({ port: 0 })
66
-
67
63
  const response = await fastify.inject({
68
64
  method: 'GET',
69
65
  url: '/events',
@@ -102,8 +98,6 @@ test('should allow setting headers in preHandler hook', async (t) => {
102
98
  await reply.sse.send({ data: 'prehandler test' })
103
99
  })
104
100
 
105
- await fastify.listen({ port: 0 })
106
-
107
101
  const response = await fastify.inject({
108
102
  method: 'GET',
109
103
  url: '/events',
@@ -19,8 +19,6 @@ test('Last-Event-ID header parsing', async (t) => {
19
19
  await reply.sse.send({ id: '43', data: 'next event' })
20
20
  })
21
21
 
22
- await fastify.listen({ port: 0 })
23
-
24
22
  const response = await fastify.inject({
25
23
  method: 'GET',
26
24
  url: '/events',
@@ -67,8 +65,6 @@ test('replay functionality', async (t) => {
67
65
  await reply.sse.send({ id: '4', data: 'latest' })
68
66
  })
69
67
 
70
- await fastify.listen({ port: 0 })
71
-
72
68
  const response = await fastify.inject({
73
69
  method: 'GET',
74
70
  url: '/events',
@@ -105,8 +101,6 @@ test('connection state during handler execution', async (t) => {
105
101
  await reply.sse.send({ data: 'connected' })
106
102
  })
107
103
 
108
- await fastify.listen({ port: 0 })
109
-
110
104
  const response = await fastify.inject({
111
105
  method: 'GET',
112
106
  url: '/events',
@@ -145,8 +139,6 @@ test('SSE interface methods exist', async (t) => {
145
139
  await reply.sse.send({ data: 'test' })
146
140
  })
147
141
 
148
- await fastify.listen({ port: 0 })
149
-
150
142
  const response = await fastify.inject({
151
143
  method: 'GET',
152
144
  url: '/events',
@@ -181,8 +173,6 @@ test('error handling in async iterator', async (t) => {
181
173
  }
182
174
  })
183
175
 
184
- await fastify.listen({ port: 0 })
185
-
186
176
  const response = await fastify.inject({
187
177
  method: 'GET',
188
178
  url: '/error-stream',
@@ -0,0 +1,263 @@
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
+ test('reply.sse.sendHeaders() should send headers manually', async (t) => {
9
+ const fastify = Fastify({ logger: false })
10
+
11
+ t.after(async () => {
12
+ await fastify.close()
13
+ })
14
+
15
+ await fastify.register(fastifySSE)
16
+
17
+ fastify.get('/events', { sse: true }, async (request, reply) => {
18
+ reply.header('X-Manual-Header', 'manual-value')
19
+ reply.header('X-Custom-ID', '12345')
20
+
21
+ // Manually call sendHeaders before sending any data
22
+ reply.sse.sendHeaders()
23
+
24
+ await reply.sse.send({ data: 'hello after manual headers' })
25
+ })
26
+
27
+ const response = await fastify.inject({
28
+ method: 'GET',
29
+ url: '/events',
30
+ headers: {
31
+ accept: 'text/event-stream'
32
+ }
33
+ })
34
+
35
+ assert.strictEqual(response.statusCode, 200)
36
+ assert.strictEqual(response.headers['x-manual-header'], 'manual-value')
37
+ assert.strictEqual(response.headers['x-custom-id'], '12345')
38
+
39
+ const body = response.body
40
+ assert.ok(body.includes('data: "hello after manual headers"'))
41
+ })
42
+
43
+ test('reply.sse.sendHeaders() should be idempotent', async (t) => {
44
+ const fastify = Fastify({ logger: false })
45
+
46
+ t.after(async () => {
47
+ await fastify.close()
48
+ })
49
+
50
+ await fastify.register(fastifySSE)
51
+
52
+ fastify.get('/events', { sse: true }, async (request, reply) => {
53
+ reply.header('X-Idempotent-Test', 'test-value')
54
+
55
+ // Call sendHeaders multiple times - should be safe
56
+ reply.sse.sendHeaders()
57
+ reply.sse.sendHeaders()
58
+ reply.sse.sendHeaders()
59
+
60
+ await reply.sse.send({ data: 'message after multiple sendHeaders calls' })
61
+ })
62
+
63
+ const response = await fastify.inject({
64
+ method: 'GET',
65
+ url: '/events',
66
+ headers: {
67
+ accept: 'text/event-stream'
68
+ }
69
+ })
70
+
71
+ assert.strictEqual(response.statusCode, 200)
72
+ assert.strictEqual(response.headers['x-idempotent-test'], 'test-value')
73
+
74
+ const body = response.body
75
+ assert.ok(body.includes('data: "message after multiple sendHeaders calls"'))
76
+ })
77
+
78
+ test('reply.sse.sendHeaders() should transfer all reply headers to raw response', async (t) => {
79
+ const fastify = Fastify({ logger: false })
80
+
81
+ t.after(async () => {
82
+ await fastify.close()
83
+ })
84
+
85
+ await fastify.register(fastifySSE)
86
+
87
+ fastify.get('/events', { sse: true }, async (request, reply) => {
88
+ // Set various types of headers
89
+ reply.header('X-Single-Header', 'single-value')
90
+ reply.headers({
91
+ 'X-Multi-Header-1': 'multi1',
92
+ 'X-Multi-Header-2': 'multi2'
93
+ })
94
+ reply.type('text/event-stream')
95
+
96
+ // Manually send headers
97
+ reply.sse.sendHeaders()
98
+
99
+ // Set more headers after sendHeaders (these won't be sent)
100
+ reply.header('X-After-Headers', 'after-value')
101
+
102
+ await reply.sse.send({ data: 'test' })
103
+ })
104
+
105
+ const response = await fastify.inject({
106
+ method: 'GET',
107
+ url: '/events',
108
+ headers: {
109
+ accept: 'text/event-stream'
110
+ }
111
+ })
112
+
113
+ assert.strictEqual(response.statusCode, 200)
114
+
115
+ // Headers set before sendHeaders() should be present
116
+ assert.strictEqual(response.headers['x-single-header'], 'single-value')
117
+ assert.strictEqual(response.headers['x-multi-header-1'], 'multi1')
118
+ assert.strictEqual(response.headers['x-multi-header-2'], 'multi2')
119
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
120
+
121
+ // Headers set after sendHeaders() should NOT be present
122
+ assert.strictEqual(response.headers['x-after-headers'], undefined)
123
+ })
124
+
125
+ test('reply.sse.sendHeaders() should work with preHandler hooks', async (t) => {
126
+ const fastify = Fastify({ logger: false })
127
+
128
+ t.after(async () => {
129
+ await fastify.close()
130
+ })
131
+
132
+ await fastify.register(fastifySSE)
133
+
134
+ fastify.get('/events', {
135
+ sse: true,
136
+ preHandler: async (request, reply) => {
137
+ reply.header('X-PreHandler-Header', 'prehandler-value')
138
+ }
139
+ }, async (request, reply) => {
140
+ reply.header('X-Handler-Header', 'handler-value')
141
+
142
+ // Manually send headers
143
+ reply.sse.sendHeaders()
144
+
145
+ await reply.sse.send({ data: 'prehandler test' })
146
+ })
147
+
148
+ const response = await fastify.inject({
149
+ method: 'GET',
150
+ url: '/events',
151
+ headers: {
152
+ accept: 'text/event-stream'
153
+ }
154
+ })
155
+
156
+ assert.strictEqual(response.statusCode, 200)
157
+ assert.strictEqual(response.headers['x-prehandler-header'], 'prehandler-value')
158
+ assert.strictEqual(response.headers['x-handler-header'], 'handler-value')
159
+
160
+ const body = response.body
161
+ assert.ok(body.includes('data: "prehandler test"'))
162
+ })
163
+
164
+ test('reply.sse.sendHeaders() should preserve default SSE headers', async (t) => {
165
+ const fastify = Fastify({ logger: false })
166
+
167
+ t.after(async () => {
168
+ await fastify.close()
169
+ })
170
+
171
+ await fastify.register(fastifySSE)
172
+
173
+ fastify.get('/events', { sse: true }, async (request, reply) => {
174
+ // Call sendHeaders without setting any custom headers
175
+ reply.sse.sendHeaders()
176
+
177
+ await reply.sse.send({ data: 'default headers preserved' })
178
+ })
179
+
180
+ const response = await fastify.inject({
181
+ method: 'GET',
182
+ url: '/events',
183
+ headers: {
184
+ accept: 'text/event-stream'
185
+ }
186
+ })
187
+
188
+ assert.strictEqual(response.statusCode, 200)
189
+
190
+ // Default SSE headers should still be present
191
+ assert.strictEqual(response.headers['content-type'], 'text/event-stream')
192
+ assert.strictEqual(response.headers['cache-control'], 'no-cache')
193
+ assert.strictEqual(response.headers['connection'], 'keep-alive')
194
+ assert.strictEqual(response.headers['x-accel-buffering'], 'no')
195
+ })
196
+
197
+ test('headers should still work when sendHeaders() is not called manually', async (t) => {
198
+ const fastify = Fastify({ logger: false })
199
+
200
+ t.after(async () => {
201
+ await fastify.close()
202
+ })
203
+
204
+ await fastify.register(fastifySSE)
205
+
206
+ fastify.get('/events', { sse: true }, async (request, reply) => {
207
+ reply.header('X-Auto-Header', 'auto-value')
208
+
209
+ // Don't call sendHeaders manually - should be called automatically
210
+ await reply.sse.send({ data: 'automatic headers' })
211
+ })
212
+
213
+ const response = await fastify.inject({
214
+ method: 'GET',
215
+ url: '/events',
216
+ headers: {
217
+ accept: 'text/event-stream'
218
+ }
219
+ })
220
+
221
+ assert.strictEqual(response.statusCode, 200)
222
+ assert.strictEqual(response.headers['x-auto-header'], 'auto-value')
223
+
224
+ const body = response.body
225
+ assert.ok(body.includes('data: "automatic headers"'))
226
+ })
227
+
228
+ test('reply.sse.sendHeaders() should work with keepAlive()', async (t) => {
229
+ const fastify = Fastify({ logger: false })
230
+
231
+ t.after(async () => {
232
+ await fastify.close()
233
+ })
234
+
235
+ await fastify.register(fastifySSE)
236
+
237
+ fastify.get('/events', { sse: true }, async (request, reply) => {
238
+ reply.header('X-KeepAlive-Header', 'keepalive-value')
239
+
240
+ reply.sse.sendHeaders()
241
+ reply.sse.keepAlive()
242
+
243
+ // Send a message after headers are sent
244
+ setTimeout(async () => {
245
+ await reply.sse.send({ data: 'delayed message' })
246
+ reply.sse.close()
247
+ }, 50)
248
+ })
249
+
250
+ const response = await fastify.inject({
251
+ method: 'GET',
252
+ url: '/events',
253
+ headers: {
254
+ accept: 'text/event-stream'
255
+ }
256
+ })
257
+
258
+ assert.strictEqual(response.statusCode, 200)
259
+ assert.strictEqual(response.headers['x-keepalive-header'], 'keepalive-value')
260
+
261
+ const body = response.body
262
+ assert.ok(body.includes('data: "delayed message"'))
263
+ })
package/types/index.d.ts CHANGED
@@ -98,6 +98,20 @@ export interface SSEReplyInterface {
98
98
  * Check if the connection is still active
99
99
  */
100
100
  readonly isConnected: boolean
101
+
102
+ /**
103
+ * Check if the connection should be kept alive after handler completion
104
+ */
105
+ readonly shouldKeepAlive: boolean
106
+
107
+ /**
108
+ * Send HTTP headers for the SSE response if not already sent.
109
+ * This method ensures headers set via reply.header() are transferred
110
+ * to the raw response before calling writeHead(200).
111
+ * Called automatically before the first SSE data is sent, but can
112
+ * also be called manually if needed.
113
+ */
114
+ sendHeaders(): void
101
115
  }
102
116
 
103
117
  declare const fastifySSE: FastifyPluginAsync<SSEPluginOptions>