use-next-sse 1.0.0 → 1.0.2
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 +603 -1
- package/dist/cjs/client/use-sse.d.ts +12 -2
- package/dist/cjs/client/use-sse.js +14 -4
- package/dist/cjs/index.d.ts +1 -1
- package/dist/client/use-sse.d.ts +12 -2
- package/dist/client/use-sse.js +14 -4
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# use-next-sse
|
|
2
|
-
[](https://github.com/alexanderkasten/use-next-sse/actions/workflows/npm-publish.yml)
|
|
2
|
+
[](https://github.com/alexanderkasten/use-next-sse/actions/workflows/npm-publish.yml) [](https://github.com/alexanderkasten/use-next-sse/actions/workflows/node.js.yml)
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
use-next-sse is a lightweight and easy-to-use React hook library for implementing Server-Sent Events (SSE) in Next.js applications, enabling real-time, unidirectional data streaming from server to client.
|
|
@@ -70,6 +70,253 @@ export default function Home() {
|
|
|
70
70
|
|
|
71
71
|
This example demonstrates a simple counter that updates every second using Server-Sent Events. The server sends updates for 10 seconds before closing the connection.
|
|
72
72
|
|
|
73
|
+
## API Reference
|
|
74
|
+
|
|
75
|
+
### Client-Side API
|
|
76
|
+
|
|
77
|
+
#### `useSSE<T>(options: SSEOptions): SSEResult<T>`
|
|
78
|
+
|
|
79
|
+
A React hook to manage Server-Sent Events (SSE) connections in your Next.js application.
|
|
80
|
+
|
|
81
|
+
**Type Parameters:**
|
|
82
|
+
- `T` - The type of the data expected from the SSE connection. Defaults to `any`.
|
|
83
|
+
|
|
84
|
+
**Parameters:**
|
|
85
|
+
|
|
86
|
+
The hook accepts a single `options` object with the following properties:
|
|
87
|
+
|
|
88
|
+
| Property | Type | Required | Default | Description |
|
|
89
|
+
|----------|------|----------|---------|-------------|
|
|
90
|
+
| `url` | `string` | Yes | - | The URL endpoint to connect to for SSE. Must be a valid URL path. |
|
|
91
|
+
| `eventName` | `string` | No | `'message'` | The name of the event to listen for. Use custom event names to handle different event types from your SSE endpoint. |
|
|
92
|
+
| `reconnect` | `boolean \| { interval?: number, maxAttempts?: number }` | No | `false` | Controls automatic reconnection behavior. Can be a boolean or an object with `interval` (ms, default: 1000) and `maxAttempts` (default: 5). |
|
|
93
|
+
| `withCredentials` | `boolean` | No | `false` | Whether to include credentials (cookies, authorization headers) in the SSE request. |
|
|
94
|
+
|
|
95
|
+
**Returns:**
|
|
96
|
+
|
|
97
|
+
An `SSEResult<T>` object with the following properties:
|
|
98
|
+
|
|
99
|
+
| Property | Type | Description |
|
|
100
|
+
|----------|------|-------------|
|
|
101
|
+
| `data` | `T \| null` | The latest data received from the SSE connection. Will be `null` until the first event is received. |
|
|
102
|
+
| `error` | `Error \| null` | Error object if an error occurred, otherwise `null`. |
|
|
103
|
+
| `lastEventId` | `string \| null` | The ID of the last event received from the server. Used for resuming connections. |
|
|
104
|
+
| `close` | `() => void` | Function to manually close the SSE connection and clean up resources. |
|
|
105
|
+
| `connectionState` | `'connecting' \| 'open' \| 'closed'` | The current state of the SSE connection. |
|
|
106
|
+
|
|
107
|
+
**Examples:**
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// Basic usage
|
|
111
|
+
const { data, error } = useSSE<{ message: string }>({
|
|
112
|
+
url: '/api/sse'
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// With custom event name
|
|
116
|
+
const { data, error } = useSSE<{ count: number }>({
|
|
117
|
+
url: '/api/sse',
|
|
118
|
+
eventName: 'counter'
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// With automatic reconnection
|
|
122
|
+
const { data, error, connectionState } = useSSE<{ message: string }>({
|
|
123
|
+
url: '/api/sse',
|
|
124
|
+
reconnect: true
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// With custom reconnection settings
|
|
128
|
+
const { data, error, close } = useSSE<{ updates: any[] }>({
|
|
129
|
+
url: '/api/sse',
|
|
130
|
+
reconnect: {
|
|
131
|
+
interval: 5000, // Wait 5 seconds between reconnection attempts
|
|
132
|
+
maxAttempts: 10 // Try up to 10 times
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// With credentials (for authenticated endpoints)
|
|
137
|
+
const { data, error } = useSSE<{ privateData: string }>({
|
|
138
|
+
url: '/api/private-sse',
|
|
139
|
+
withCredentials: true
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// Using connection state
|
|
143
|
+
const { data, connectionState } = useSSE({ url: '/api/sse' });
|
|
144
|
+
|
|
145
|
+
if (connectionState === 'connecting') {
|
|
146
|
+
return <div>Connecting...</div>;
|
|
147
|
+
}
|
|
148
|
+
if (connectionState === 'closed') {
|
|
149
|
+
return <div>Connection closed</div>;
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### `SSEOptions` Type
|
|
154
|
+
|
|
155
|
+
TypeScript interface for the options passed to `useSSE`.
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
type SSEOptions = {
|
|
159
|
+
url: string;
|
|
160
|
+
eventName?: string;
|
|
161
|
+
reconnect?: boolean | {
|
|
162
|
+
interval?: number;
|
|
163
|
+
maxAttempts?: number;
|
|
164
|
+
};
|
|
165
|
+
withCredentials?: boolean;
|
|
166
|
+
};
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### `SSEResult<T>` Type
|
|
170
|
+
|
|
171
|
+
TypeScript interface for the return value of `useSSE`.
|
|
172
|
+
|
|
173
|
+
```typescript
|
|
174
|
+
interface SSEResult<T> {
|
|
175
|
+
data: T | null;
|
|
176
|
+
error: Error | null;
|
|
177
|
+
lastEventId: string | null;
|
|
178
|
+
close: () => void;
|
|
179
|
+
connectionState: 'connecting' | 'open' | 'closed';
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Server-Side API
|
|
184
|
+
|
|
185
|
+
#### `createSSEHandler(callback: SSECallback, options?: SSEOptions): NextHandler`
|
|
186
|
+
|
|
187
|
+
Creates a Next.js API route handler for Server-Sent Events.
|
|
188
|
+
|
|
189
|
+
**Parameters:**
|
|
190
|
+
|
|
191
|
+
| Parameter | Type | Required | Description |
|
|
192
|
+
|-----------|------|----------|-------------|
|
|
193
|
+
| `callback` | `SSECallback` | Yes | A function that handles the SSE connection. Receives `send`, `close`, and `context` parameters. |
|
|
194
|
+
| `options` | `{ onClose?: Destructor }` | No | Optional configuration object with an `onClose` cleanup function. |
|
|
195
|
+
|
|
196
|
+
**Callback Parameters:**
|
|
197
|
+
|
|
198
|
+
The `callback` function receives three parameters:
|
|
199
|
+
|
|
200
|
+
1. **`send(data: any, eventName?: string): void`**
|
|
201
|
+
- Sends data to the client over the SSE connection
|
|
202
|
+
- `data`: The data to send (will be JSON stringified)
|
|
203
|
+
- `eventName` (optional): The event name for the client to listen to
|
|
204
|
+
|
|
205
|
+
2. **`close(): void`**
|
|
206
|
+
- Closes the SSE connection and triggers cleanup functions
|
|
207
|
+
|
|
208
|
+
3. **`context: { lastEventId: string | null; onClose: (destructor: Destructor) => void }`**
|
|
209
|
+
- `lastEventId`: The last event ID received by the client (for reconnections)
|
|
210
|
+
- `onClose`: Function to register a cleanup handler that runs when the connection closes
|
|
211
|
+
|
|
212
|
+
**Returns:**
|
|
213
|
+
|
|
214
|
+
A Next.js request handler function that can be exported as `GET`, `POST`, etc.
|
|
215
|
+
|
|
216
|
+
**Response Headers:**
|
|
217
|
+
|
|
218
|
+
The handler automatically sets these response headers:
|
|
219
|
+
- `Content-Type: text/event-stream`
|
|
220
|
+
- `Cache-Control: no-cache, no-transform`
|
|
221
|
+
- `Connection: keep-alive`
|
|
222
|
+
|
|
223
|
+
**Examples:**
|
|
224
|
+
|
|
225
|
+
```typescript
|
|
226
|
+
// Basic counter example
|
|
227
|
+
export const GET = createSSEHandler((send, close) => {
|
|
228
|
+
let count = 0;
|
|
229
|
+
const interval = setInterval(() => {
|
|
230
|
+
send({ count: count++ }, 'counter');
|
|
231
|
+
if (count >= 10) {
|
|
232
|
+
clearInterval(interval);
|
|
233
|
+
close();
|
|
234
|
+
}
|
|
235
|
+
}, 1000);
|
|
236
|
+
|
|
237
|
+
// Return cleanup function
|
|
238
|
+
return () => {
|
|
239
|
+
clearInterval(interval);
|
|
240
|
+
};
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// Example with async operations
|
|
244
|
+
export const GET = createSSEHandler((send, close) => {
|
|
245
|
+
const fetchData = async () => {
|
|
246
|
+
const data = await fetch('https://api.example.com/data');
|
|
247
|
+
send(await data.json(), 'data');
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// Don't await - let it run in background
|
|
251
|
+
fetchData();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// Example with context and lastEventId (resuming connections)
|
|
255
|
+
export const GET = createSSEHandler((send, close, { lastEventId }) => {
|
|
256
|
+
if (lastEventId) {
|
|
257
|
+
console.log('Client reconnected from event:', lastEventId);
|
|
258
|
+
// Resume from where client left off
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Send events...
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// Example with context.onClose
|
|
265
|
+
export const GET = createSSEHandler(async (send, close, { onClose }) => {
|
|
266
|
+
const db = await connectToDatabase();
|
|
267
|
+
|
|
268
|
+
// Register cleanup early, even before long-running operations
|
|
269
|
+
onClose(() => {
|
|
270
|
+
db.disconnect();
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// Long-running operation
|
|
274
|
+
await setupLiveQuery(db, (data) => {
|
|
275
|
+
send(data, 'update');
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
// Example with global onClose option
|
|
280
|
+
export const GET = createSSEHandler(
|
|
281
|
+
(send, close) => {
|
|
282
|
+
// Your logic here
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
onClose: () => {
|
|
286
|
+
console.log('Connection closed');
|
|
287
|
+
// This runs even if callback hasn't been called yet
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
);
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**Important Notes:**
|
|
294
|
+
|
|
295
|
+
- **Avoid blocking operations**: Don't `await` long-running operations directly in the callback, as this delays sending the initial response to the client. Instead, wrap async operations in a function and call it without awaiting.
|
|
296
|
+
|
|
297
|
+
```typescript
|
|
298
|
+
// ❌ Bad - blocks response
|
|
299
|
+
export const GET = createSSEHandler(async (send, close) => {
|
|
300
|
+
await someLongOperation(); // Client waits for this
|
|
301
|
+
send({ data: 'hello' });
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// ✅ Good - response sent immediately
|
|
305
|
+
export const GET = createSSEHandler((send, close) => {
|
|
306
|
+
const process = async () => {
|
|
307
|
+
await someLongOperation();
|
|
308
|
+
send({ data: 'hello' });
|
|
309
|
+
};
|
|
310
|
+
process(); // Don't await
|
|
311
|
+
});
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
- **Cleanup priority**: If multiple cleanup functions are registered (via return value, `context.onClose`, and `options.onClose`), the first one registered takes precedence and a warning is logged for subsequent attempts.
|
|
315
|
+
|
|
316
|
+
- **Next.js configuration**: Always set `export const dynamic = 'force-dynamic';` in your route file to prevent Next.js from caching the SSE endpoint.
|
|
317
|
+
|
|
318
|
+
## Advanced Usage
|
|
319
|
+
|
|
73
320
|
### Destructor in `createSSEHandler`
|
|
74
321
|
|
|
75
322
|
When using the `createSSEHandler` function in the `use-next-sse` library, it is important to understand the role of the destructor. The destructor is a cleanup function that is called when the SSE connection is closed. This allows you to perform any necessary cleanup tasks, such as closing database connections, stopping intervals, or clearing resources.
|
|
@@ -136,3 +383,358 @@ const handler = createSSEHandler(async(send, close, { onClose }) => {
|
|
|
136
383
|
|
|
137
384
|
export default handler;
|
|
138
385
|
```
|
|
386
|
+
|
|
387
|
+
## Common Use Cases
|
|
388
|
+
|
|
389
|
+
### Real-time Notifications
|
|
390
|
+
|
|
391
|
+
```typescript
|
|
392
|
+
// Server: app/api/notifications/route.ts
|
|
393
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
394
|
+
|
|
395
|
+
export const dynamic = 'force-dynamic';
|
|
396
|
+
|
|
397
|
+
export const GET = createSSEHandler((send, close, { onClose }) => {
|
|
398
|
+
const userId = // ... get from auth
|
|
399
|
+
|
|
400
|
+
// Subscribe to notification service
|
|
401
|
+
const subscription = notificationService.subscribe(userId, (notification) => {
|
|
402
|
+
send(notification, 'notification');
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
onClose(() => {
|
|
406
|
+
subscription.unsubscribe();
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
// Client: components/NotificationBell.tsx
|
|
411
|
+
'use client';
|
|
412
|
+
|
|
413
|
+
import { useSSE } from 'use-next-sse';
|
|
414
|
+
|
|
415
|
+
export function NotificationBell() {
|
|
416
|
+
const { data, error } = useSSE<Notification>({
|
|
417
|
+
url: '/api/notifications',
|
|
418
|
+
eventName: 'notification',
|
|
419
|
+
reconnect: true
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
if (error) return <div>Error loading notifications</div>;
|
|
423
|
+
|
|
424
|
+
return (
|
|
425
|
+
<div className="notification-bell">
|
|
426
|
+
{data && <span className="badge">{data.unreadCount}</span>}
|
|
427
|
+
</div>
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
### Live Data Dashboard
|
|
433
|
+
|
|
434
|
+
```typescript
|
|
435
|
+
// Server: app/api/metrics/route.ts
|
|
436
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
437
|
+
|
|
438
|
+
export const dynamic = 'force-dynamic';
|
|
439
|
+
|
|
440
|
+
export const GET = createSSEHandler((send, close) => {
|
|
441
|
+
const interval = setInterval(async () => {
|
|
442
|
+
const metrics = await fetchMetrics();
|
|
443
|
+
send(metrics, 'metrics');
|
|
444
|
+
}, 5000);
|
|
445
|
+
|
|
446
|
+
return () => clearInterval(interval);
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
// Client: components/Dashboard.tsx
|
|
450
|
+
'use client';
|
|
451
|
+
|
|
452
|
+
import { useSSE } from 'use-next-sse';
|
|
453
|
+
|
|
454
|
+
interface Metrics {
|
|
455
|
+
activeUsers: number;
|
|
456
|
+
requestsPerSecond: number;
|
|
457
|
+
errorRate: number;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function Dashboard() {
|
|
461
|
+
const { data, connectionState } = useSSE<Metrics>({
|
|
462
|
+
url: '/api/metrics',
|
|
463
|
+
eventName: 'metrics',
|
|
464
|
+
reconnect: { interval: 3000, maxAttempts: 10 }
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
return (
|
|
468
|
+
<div>
|
|
469
|
+
<div className={`status status-${connectionState}`}>
|
|
470
|
+
{connectionState}
|
|
471
|
+
</div>
|
|
472
|
+
{data && (
|
|
473
|
+
<div className="metrics">
|
|
474
|
+
<MetricCard title="Active Users" value={data.activeUsers} />
|
|
475
|
+
<MetricCard title="Requests/sec" value={data.requestsPerSecond} />
|
|
476
|
+
<MetricCard title="Error Rate" value={`${data.errorRate}%`} />
|
|
477
|
+
</div>
|
|
478
|
+
)}
|
|
479
|
+
</div>
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
### Progress Tracking
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
// Server: app/api/export/route.ts
|
|
488
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
489
|
+
|
|
490
|
+
export const dynamic = 'force-dynamic';
|
|
491
|
+
|
|
492
|
+
export const GET = createSSEHandler(async (send, close) => {
|
|
493
|
+
const exportData = async () => {
|
|
494
|
+
const total = await getTotalRecords();
|
|
495
|
+
let processed = 0;
|
|
496
|
+
|
|
497
|
+
for await (const chunk of fetchDataInChunks()) {
|
|
498
|
+
await processChunk(chunk);
|
|
499
|
+
processed += chunk.length;
|
|
500
|
+
|
|
501
|
+
send({
|
|
502
|
+
progress: (processed / total) * 100,
|
|
503
|
+
processed,
|
|
504
|
+
total
|
|
505
|
+
}, 'progress');
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
send({ completed: true }, 'complete');
|
|
509
|
+
close();
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
exportData();
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
// Client: components/ExportProgress.tsx
|
|
516
|
+
'use client';
|
|
517
|
+
|
|
518
|
+
import { useSSE } from 'use-next-sse';
|
|
519
|
+
|
|
520
|
+
interface ProgressData {
|
|
521
|
+
progress: number;
|
|
522
|
+
processed: number;
|
|
523
|
+
total: number;
|
|
524
|
+
completed?: boolean;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
export function ExportProgress() {
|
|
528
|
+
const { data, error } = useSSE<ProgressData>({
|
|
529
|
+
url: '/api/export',
|
|
530
|
+
eventName: 'progress'
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
if (error) return <div>Export failed: {error.message}</div>;
|
|
534
|
+
if (!data) return <div>Starting export...</div>;
|
|
535
|
+
if (data.completed) return <div>Export completed!</div>;
|
|
536
|
+
|
|
537
|
+
return (
|
|
538
|
+
<div>
|
|
539
|
+
<ProgressBar value={data.progress} />
|
|
540
|
+
<p>{data.processed} / {data.total} records processed</p>
|
|
541
|
+
</div>
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
### Chat Application
|
|
547
|
+
|
|
548
|
+
```typescript
|
|
549
|
+
// Server: app/api/chat/[roomId]/route.ts
|
|
550
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
551
|
+
|
|
552
|
+
export const dynamic = 'force-dynamic';
|
|
553
|
+
|
|
554
|
+
export const GET = createSSEHandler((send, close, { lastEventId }) => {
|
|
555
|
+
const roomId = // ... get from params
|
|
556
|
+
|
|
557
|
+
// If reconnecting, send missed messages
|
|
558
|
+
if (lastEventId) {
|
|
559
|
+
const missedMessages = getMessagesSince(roomId, lastEventId);
|
|
560
|
+
missedMessages.forEach(msg => send(msg, 'message'));
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Subscribe to new messages
|
|
564
|
+
const unsubscribe = chatService.subscribe(roomId, (message) => {
|
|
565
|
+
send(message, 'message');
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
return unsubscribe;
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
// Client: components/ChatRoom.tsx
|
|
572
|
+
'use client';
|
|
573
|
+
|
|
574
|
+
import { useSSE } from 'use-next-sse';
|
|
575
|
+
import { useState, useEffect } from 'react';
|
|
576
|
+
|
|
577
|
+
interface Message {
|
|
578
|
+
id: string;
|
|
579
|
+
user: string;
|
|
580
|
+
text: string;
|
|
581
|
+
timestamp: number;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export function ChatRoom({ roomId }: { roomId: string }) {
|
|
585
|
+
const [messages, setMessages] = useState<Message[]>([]);
|
|
586
|
+
|
|
587
|
+
const { data, connectionState } = useSSE<Message>({
|
|
588
|
+
url: `/api/chat/${roomId}`,
|
|
589
|
+
eventName: 'message',
|
|
590
|
+
reconnect: true
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
// Add new messages to the list
|
|
594
|
+
useEffect(() => {
|
|
595
|
+
if (data) {
|
|
596
|
+
setMessages(prev => [...prev, data]);
|
|
597
|
+
}
|
|
598
|
+
}, [data]);
|
|
599
|
+
|
|
600
|
+
return (
|
|
601
|
+
<div className="chat-room">
|
|
602
|
+
<div className="status">{connectionState}</div>
|
|
603
|
+
<div className="messages">
|
|
604
|
+
{messages.map(msg => (
|
|
605
|
+
<ChatMessage key={msg.id} message={msg} />
|
|
606
|
+
))}
|
|
607
|
+
</div>
|
|
608
|
+
</div>
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
### Multiple Event Types
|
|
614
|
+
|
|
615
|
+
```typescript
|
|
616
|
+
// Server: app/api/events/route.ts
|
|
617
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
618
|
+
|
|
619
|
+
export const dynamic = 'force-dynamic';
|
|
620
|
+
|
|
621
|
+
export const GET = createSSEHandler((send, close) => {
|
|
622
|
+
// Send different event types
|
|
623
|
+
const interval1 = setInterval(() => {
|
|
624
|
+
send({ temperature: Math.random() * 30 }, 'temperature');
|
|
625
|
+
}, 1000);
|
|
626
|
+
|
|
627
|
+
const interval2 = setInterval(() => {
|
|
628
|
+
send({ humidity: Math.random() * 100 }, 'humidity');
|
|
629
|
+
}, 2000);
|
|
630
|
+
|
|
631
|
+
const interval3 = setInterval(() => {
|
|
632
|
+
send({ pressure: Math.random() * 1000 + 900 }, 'pressure');
|
|
633
|
+
}, 3000);
|
|
634
|
+
|
|
635
|
+
return () => {
|
|
636
|
+
clearInterval(interval1);
|
|
637
|
+
clearInterval(interval2);
|
|
638
|
+
clearInterval(interval3);
|
|
639
|
+
};
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
// Client: components/SensorMonitor.tsx
|
|
643
|
+
'use client';
|
|
644
|
+
|
|
645
|
+
import { useSSE } from 'use-next-sse';
|
|
646
|
+
|
|
647
|
+
export function SensorMonitor() {
|
|
648
|
+
const temperature = useSSE<{ temperature: number }>({
|
|
649
|
+
url: '/api/events',
|
|
650
|
+
eventName: 'temperature'
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
const humidity = useSSE<{ humidity: number }>({
|
|
654
|
+
url: '/api/events',
|
|
655
|
+
eventName: 'humidity'
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
const pressure = useSSE<{ pressure: number }>({
|
|
659
|
+
url: '/api/events',
|
|
660
|
+
eventName: 'pressure'
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
return (
|
|
664
|
+
<div className="sensors">
|
|
665
|
+
<Sensor label="Temperature" value={temperature.data?.temperature} unit="°C" />
|
|
666
|
+
<Sensor label="Humidity" value={humidity.data?.humidity} unit="%" />
|
|
667
|
+
<Sensor label="Pressure" value={pressure.data?.pressure} unit="hPa" />
|
|
668
|
+
</div>
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
## Error Handling
|
|
674
|
+
|
|
675
|
+
```typescript
|
|
676
|
+
'use client';
|
|
677
|
+
|
|
678
|
+
import { useSSE } from 'use-next-sse';
|
|
679
|
+
import { useEffect } from 'react';
|
|
680
|
+
|
|
681
|
+
export function MyComponent() {
|
|
682
|
+
const { data, error, connectionState, close } = useSSE({
|
|
683
|
+
url: '/api/sse',
|
|
684
|
+
reconnect: { interval: 2000, maxAttempts: 3 }
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
useEffect(() => {
|
|
688
|
+
if (error) {
|
|
689
|
+
console.error('SSE Error:', error);
|
|
690
|
+
// Handle error - show notification, etc.
|
|
691
|
+
}
|
|
692
|
+
}, [error]);
|
|
693
|
+
|
|
694
|
+
useEffect(() => {
|
|
695
|
+
if (connectionState === 'closed' && !error) {
|
|
696
|
+
// Connection closed gracefully
|
|
697
|
+
console.log('Connection closed by server');
|
|
698
|
+
}
|
|
699
|
+
}, [connectionState, error]);
|
|
700
|
+
|
|
701
|
+
// Manual cleanup on component unmount or user action
|
|
702
|
+
useEffect(() => {
|
|
703
|
+
return () => {
|
|
704
|
+
close();
|
|
705
|
+
};
|
|
706
|
+
}, [close]);
|
|
707
|
+
|
|
708
|
+
if (error) {
|
|
709
|
+
return (
|
|
710
|
+
<div className="error">
|
|
711
|
+
<p>Connection error: {error.message}</p>
|
|
712
|
+
<button onClick={() => window.location.reload()}>Retry</button>
|
|
713
|
+
</div>
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
return <div>{/* Your component */}</div>;
|
|
718
|
+
}
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
## Browser Compatibility
|
|
722
|
+
|
|
723
|
+
This library uses the native `EventSource` API, which is supported in all modern browsers:
|
|
724
|
+
- Chrome/Edge: ✅
|
|
725
|
+
- Firefox: ✅
|
|
726
|
+
- Safari: ✅
|
|
727
|
+
- Opera: ✅
|
|
728
|
+
- IE: ❌ (No longer supported)
|
|
729
|
+
|
|
730
|
+
## License
|
|
731
|
+
|
|
732
|
+
MIT
|
|
733
|
+
|
|
734
|
+
## Contributing
|
|
735
|
+
|
|
736
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
737
|
+
|
|
738
|
+
## Support
|
|
739
|
+
|
|
740
|
+
If you encounter any issues or have questions, please [open an issue](https://github.com/alexanderkasten/use-next-sse/issues) on GitHub.
|
|
@@ -49,7 +49,18 @@ export type SSEOptions = {
|
|
|
49
49
|
*/
|
|
50
50
|
withCredentials?: boolean;
|
|
51
51
|
};
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The result object returned by the useSSE hook.
|
|
54
|
+
* @template T - The type of the data expected from the SSE.
|
|
55
|
+
* @property {T | null} data - The latest data received from the SSE connection, or null if no data has been received yet.
|
|
56
|
+
* @property {Error | null} error - The error object if an error occurred, or null if no error has occurred.
|
|
57
|
+
* @property {string | null} lastEventId - The ID of the last event received from the server, or null if no event has been received yet.
|
|
58
|
+
* @property {() => void} close - A function to manually close the SSE connection and clean up resources.
|
|
59
|
+
* @property {'connecting' | 'open' | 'closed'} connectionState - The current state of the SSE connection.
|
|
60
|
+
* @example
|
|
61
|
+
* const { data, error, lastEventId, close, connectionState }: SSEResult<MyDataType> = useSSE({ url: '/api/sse' });
|
|
62
|
+
*/
|
|
63
|
+
export interface SSEResult<T> {
|
|
53
64
|
data: T | null;
|
|
54
65
|
error: Error | null;
|
|
55
66
|
lastEventId: string | null;
|
|
@@ -95,4 +106,3 @@ interface SSEResult<T> {
|
|
|
95
106
|
* }, [data]);
|
|
96
107
|
*/
|
|
97
108
|
export declare function useSSE<T = any>({ url, eventName, reconnect, withCredentials, }: SSEOptions): SSEResult<T>;
|
|
98
|
-
export {};
|
|
@@ -40,7 +40,10 @@ function useSSE({ url, eventName = 'message', reconnect = false, withCredentials
|
|
|
40
40
|
}
|
|
41
41
|
cleanupRef.current();
|
|
42
42
|
setConnectionState('closed');
|
|
43
|
-
}, [
|
|
43
|
+
}, []);
|
|
44
|
+
const reconnectEnabled = !!reconnect;
|
|
45
|
+
const reconnectInterval = typeof reconnect === 'object' ? reconnect.interval : undefined;
|
|
46
|
+
const reconnectMaxAttempts = typeof reconnect === 'object' ? reconnect.maxAttempts : undefined;
|
|
44
47
|
(0, react_1.useEffect)(() => {
|
|
45
48
|
const connect = () => {
|
|
46
49
|
setConnectionState('connecting');
|
|
@@ -70,7 +73,8 @@ function useSSE({ url, eventName = 'message', reconnect = false, withCredentials
|
|
|
70
73
|
sse_manager_1.sseManager.removeEventListener(url, eventName, handleMessage);
|
|
71
74
|
source.removeEventListener('open', handleOpen);
|
|
72
75
|
source.removeEventListener('error', handleError);
|
|
73
|
-
|
|
76
|
+
sse_manager_1.sseManager.releaseConnection(url);
|
|
77
|
+
cleanupRef.current = connect();
|
|
74
78
|
}, interval);
|
|
75
79
|
}
|
|
76
80
|
else {
|
|
@@ -89,15 +93,21 @@ function useSSE({ url, eventName = 'message', reconnect = false, withCredentials
|
|
|
89
93
|
source.addEventListener('error', handleError);
|
|
90
94
|
return destructor;
|
|
91
95
|
};
|
|
96
|
+
if (url === '') {
|
|
97
|
+
if (connectionState !== 'closed') {
|
|
98
|
+
close();
|
|
99
|
+
}
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
92
102
|
const cleanup = connect();
|
|
93
103
|
cleanupRef.current = cleanup;
|
|
94
104
|
return () => {
|
|
95
105
|
if (reconnectTimeout.current) {
|
|
96
106
|
clearTimeout(reconnectTimeout.current);
|
|
97
107
|
}
|
|
98
|
-
|
|
108
|
+
cleanupRef.current();
|
|
99
109
|
};
|
|
100
|
-
}, [url, eventName,
|
|
110
|
+
}, [url, eventName, withCredentials, reconnectEnabled, reconnectInterval, reconnectMaxAttempts]);
|
|
101
111
|
return { data, error, lastEventId, close, connectionState };
|
|
102
112
|
}
|
|
103
113
|
exports.useSSE = useSSE;
|
package/dist/cjs/index.d.ts
CHANGED
package/dist/client/use-sse.d.ts
CHANGED
|
@@ -49,7 +49,18 @@ export type SSEOptions = {
|
|
|
49
49
|
*/
|
|
50
50
|
withCredentials?: boolean;
|
|
51
51
|
};
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The result object returned by the useSSE hook.
|
|
54
|
+
* @template T - The type of the data expected from the SSE.
|
|
55
|
+
* @property {T | null} data - The latest data received from the SSE connection, or null if no data has been received yet.
|
|
56
|
+
* @property {Error | null} error - The error object if an error occurred, or null if no error has occurred.
|
|
57
|
+
* @property {string | null} lastEventId - The ID of the last event received from the server, or null if no event has been received yet.
|
|
58
|
+
* @property {() => void} close - A function to manually close the SSE connection and clean up resources.
|
|
59
|
+
* @property {'connecting' | 'open' | 'closed'} connectionState - The current state of the SSE connection.
|
|
60
|
+
* @example
|
|
61
|
+
* const { data, error, lastEventId, close, connectionState }: SSEResult<MyDataType> = useSSE({ url: '/api/sse' });
|
|
62
|
+
*/
|
|
63
|
+
export interface SSEResult<T> {
|
|
53
64
|
data: T | null;
|
|
54
65
|
error: Error | null;
|
|
55
66
|
lastEventId: string | null;
|
|
@@ -95,4 +106,3 @@ interface SSEResult<T> {
|
|
|
95
106
|
* }, [data]);
|
|
96
107
|
*/
|
|
97
108
|
export declare function useSSE<T = any>({ url, eventName, reconnect, withCredentials, }: SSEOptions): SSEResult<T>;
|
|
98
|
-
export {};
|
package/dist/client/use-sse.js
CHANGED
|
@@ -37,7 +37,10 @@ export function useSSE({ url, eventName = 'message', reconnect = false, withCred
|
|
|
37
37
|
}
|
|
38
38
|
cleanupRef.current();
|
|
39
39
|
setConnectionState('closed');
|
|
40
|
-
}, [
|
|
40
|
+
}, []);
|
|
41
|
+
const reconnectEnabled = !!reconnect;
|
|
42
|
+
const reconnectInterval = typeof reconnect === 'object' ? reconnect.interval : undefined;
|
|
43
|
+
const reconnectMaxAttempts = typeof reconnect === 'object' ? reconnect.maxAttempts : undefined;
|
|
41
44
|
useEffect(() => {
|
|
42
45
|
const connect = () => {
|
|
43
46
|
setConnectionState('connecting');
|
|
@@ -67,7 +70,8 @@ export function useSSE({ url, eventName = 'message', reconnect = false, withCred
|
|
|
67
70
|
sseManager.removeEventListener(url, eventName, handleMessage);
|
|
68
71
|
source.removeEventListener('open', handleOpen);
|
|
69
72
|
source.removeEventListener('error', handleError);
|
|
70
|
-
|
|
73
|
+
sseManager.releaseConnection(url);
|
|
74
|
+
cleanupRef.current = connect();
|
|
71
75
|
}, interval);
|
|
72
76
|
}
|
|
73
77
|
else {
|
|
@@ -86,14 +90,20 @@ export function useSSE({ url, eventName = 'message', reconnect = false, withCred
|
|
|
86
90
|
source.addEventListener('error', handleError);
|
|
87
91
|
return destructor;
|
|
88
92
|
};
|
|
93
|
+
if (url === '') {
|
|
94
|
+
if (connectionState !== 'closed') {
|
|
95
|
+
close();
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
89
99
|
const cleanup = connect();
|
|
90
100
|
cleanupRef.current = cleanup;
|
|
91
101
|
return () => {
|
|
92
102
|
if (reconnectTimeout.current) {
|
|
93
103
|
clearTimeout(reconnectTimeout.current);
|
|
94
104
|
}
|
|
95
|
-
|
|
105
|
+
cleanupRef.current();
|
|
96
106
|
};
|
|
97
|
-
}, [url, eventName,
|
|
107
|
+
}, [url, eventName, withCredentials, reconnectEnabled, reconnectInterval, reconnectMaxAttempts]);
|
|
98
108
|
return { data, error, lastEventId, close, connectionState };
|
|
99
109
|
}
|
package/dist/index.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "use-next-sse",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "A lightweight Server-Sent Events (SSE) library for Next.js, enabling real-time, unidirectional data streaming from server to client",
|
|
5
5
|
"main": "dist/cjs/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|