use-next-sse 0.0.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/LICENSE +21 -0
- package/README.md +68 -0
- package/dist/client/use-sse.d.ts +11 -0
- package/dist/client/use-sse.js +68 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/server/sse-server.d.ts +18 -0
- package/dist/server/sse-server.js +62 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Alex
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# use-next-sse
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
\`\`\`bash
|
|
8
|
+
npm install use-next-sse
|
|
9
|
+
\`\`\`
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
### Server-Side (Next.js API Route)
|
|
14
|
+
|
|
15
|
+
Create a new file `app/api/sse/route.ts` with the following content:
|
|
16
|
+
|
|
17
|
+
\`\`\`typescript
|
|
18
|
+
import { createSSEHandler } from 'use-next-sse';
|
|
19
|
+
|
|
20
|
+
export const GET = createSSEHandler(async (sse) => {
|
|
21
|
+
let count = 0;
|
|
22
|
+
const interval = setInterval(() => {
|
|
23
|
+
sse.send({ count: count++ }, 'counter');
|
|
24
|
+
if (count > 10) {
|
|
25
|
+
clearInterval(interval);
|
|
26
|
+
sse.close();
|
|
27
|
+
}
|
|
28
|
+
}, 1000);
|
|
29
|
+
});
|
|
30
|
+
\`\`\`
|
|
31
|
+
|
|
32
|
+
### Client-Side (React Component)
|
|
33
|
+
|
|
34
|
+
Create a new file `app/components/Counter.tsx` with the following content:
|
|
35
|
+
|
|
36
|
+
\`\`\`typescript
|
|
37
|
+
'use client'
|
|
38
|
+
|
|
39
|
+
import { useSSE } from 'use-next-sse';
|
|
40
|
+
|
|
41
|
+
export default function Counter() {
|
|
42
|
+
const { data, error } = useSSE('/api/sse', 'counter');
|
|
43
|
+
|
|
44
|
+
if (error) return <div>Error: {error.message}</div>;
|
|
45
|
+
if (!data) return <div>Loading...</div>;
|
|
46
|
+
|
|
47
|
+
return <div>Count: {data.count}</div>;
|
|
48
|
+
}
|
|
49
|
+
\`\`\`
|
|
50
|
+
|
|
51
|
+
### Usage in a Page
|
|
52
|
+
|
|
53
|
+
Use the `Counter` component in a page, for example in `app/page.tsx`:
|
|
54
|
+
|
|
55
|
+
\`\`\`typescript
|
|
56
|
+
import Counter from './components/Counter';
|
|
57
|
+
|
|
58
|
+
export default function Home() {
|
|
59
|
+
return (
|
|
60
|
+
<main>
|
|
61
|
+
<h1>SSE Counter Example</h1>
|
|
62
|
+
<Counter />
|
|
63
|
+
</main>
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
\`\`\`
|
|
67
|
+
|
|
68
|
+
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.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface SSEOptions {
|
|
2
|
+
onMessage?: (event: MessageEvent) => void;
|
|
3
|
+
onError?: (error: Error) => void;
|
|
4
|
+
reconnectInterval?: number;
|
|
5
|
+
maxReconnectAttempts?: number;
|
|
6
|
+
}
|
|
7
|
+
export declare function useSSE(url: string, eventName?: string, options?: SSEOptions): {
|
|
8
|
+
data: any;
|
|
9
|
+
error: Error | null;
|
|
10
|
+
close: () => void;
|
|
11
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { useState, useEffect, useRef } from 'react';
|
|
2
|
+
export function useSSE(url, eventName, options = {}) {
|
|
3
|
+
const [data, setData] = useState(null);
|
|
4
|
+
const [error, setError] = useState(null);
|
|
5
|
+
const eventSourceRef = useRef(null);
|
|
6
|
+
const reconnectAttemptsRef = useRef(0);
|
|
7
|
+
const reconnectInterval = options.reconnectInterval || 1000;
|
|
8
|
+
const maxReconnectAttempts = options.maxReconnectAttempts || 5;
|
|
9
|
+
useEffect(() => {
|
|
10
|
+
let timeoutId;
|
|
11
|
+
const messageHandler = (event) => {
|
|
12
|
+
var _a, _b;
|
|
13
|
+
try {
|
|
14
|
+
const parsedData = JSON.parse(event.data);
|
|
15
|
+
setData(parsedData);
|
|
16
|
+
(_a = options.onMessage) === null || _a === void 0 ? void 0 : _a.call(options, event);
|
|
17
|
+
reconnectAttemptsRef.current = 0;
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
const parseError = new Error(`Failed to parse SSE data: ${err.message}`);
|
|
21
|
+
setError(parseError);
|
|
22
|
+
(_b = options.onError) === null || _b === void 0 ? void 0 : _b.call(options, parseError);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const connect = () => {
|
|
26
|
+
const eventSource = new EventSource(url);
|
|
27
|
+
if (eventName) {
|
|
28
|
+
eventSource.addEventListener(eventName, messageHandler);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
eventSource.onmessage = messageHandler;
|
|
32
|
+
}
|
|
33
|
+
eventSource.onerror = (event) => {
|
|
34
|
+
var _a;
|
|
35
|
+
const sseError = new Error('SSE connection error');
|
|
36
|
+
setError(sseError);
|
|
37
|
+
(_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, sseError);
|
|
38
|
+
eventSource.close();
|
|
39
|
+
if (reconnectAttemptsRef.current < maxReconnectAttempts) {
|
|
40
|
+
reconnectAttemptsRef.current++;
|
|
41
|
+
console.log(`Reconnecting... Attempt ${reconnectAttemptsRef.current} of ${maxReconnectAttempts}`);
|
|
42
|
+
timeoutId = window.setTimeout(connect, reconnectInterval);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
console.error('Max reconnect attempts reached. Giving up.');
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
eventSourceRef.current = eventSource;
|
|
49
|
+
};
|
|
50
|
+
connect();
|
|
51
|
+
return () => {
|
|
52
|
+
if (eventSourceRef.current) {
|
|
53
|
+
if (eventName) {
|
|
54
|
+
eventSourceRef.current.removeEventListener(eventName, messageHandler);
|
|
55
|
+
}
|
|
56
|
+
eventSourceRef.current.close();
|
|
57
|
+
}
|
|
58
|
+
window.clearTimeout(timeoutId);
|
|
59
|
+
};
|
|
60
|
+
}, [url, eventName, options, reconnectInterval, maxReconnectAttempts]);
|
|
61
|
+
const close = () => {
|
|
62
|
+
if (eventSourceRef.current) {
|
|
63
|
+
eventSourceRef.current.close();
|
|
64
|
+
eventSourceRef.current = null;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
return { data, error, close };
|
|
68
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
export type SSEConfig = {
|
|
3
|
+
reconnectInterval?: number;
|
|
4
|
+
maxReconnectAttempts?: number;
|
|
5
|
+
};
|
|
6
|
+
export declare class SSEConnection {
|
|
7
|
+
private encoder;
|
|
8
|
+
private controller;
|
|
9
|
+
private initializePromise;
|
|
10
|
+
private resolveInitialize;
|
|
11
|
+
private config;
|
|
12
|
+
constructor(config?: SSEConfig);
|
|
13
|
+
initialize(): Promise<void>;
|
|
14
|
+
send(data: any, event?: string): void;
|
|
15
|
+
close(): void;
|
|
16
|
+
getResponse(): NextResponse<unknown>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createSSEHandler(handler: (sse: SSEConnection) => Promise<void>, config?: SSEConfig): () => Promise<NextResponse<unknown>>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
export class SSEConnection {
|
|
3
|
+
constructor(config = {}) {
|
|
4
|
+
this.resolveInitialize = null;
|
|
5
|
+
this.encoder = new TextEncoder();
|
|
6
|
+
this.initializePromise = new Promise((resolve) => {
|
|
7
|
+
this.resolveInitialize = resolve;
|
|
8
|
+
});
|
|
9
|
+
this.config = {
|
|
10
|
+
reconnectInterval: config.reconnectInterval || 1000,
|
|
11
|
+
maxReconnectAttempts: config.maxReconnectAttempts || 5,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
async initialize() {
|
|
15
|
+
await this.initializePromise;
|
|
16
|
+
}
|
|
17
|
+
send(data, event) {
|
|
18
|
+
if (!this.controller) {
|
|
19
|
+
throw new Error('SSEConnection not initialized. Call initialize() first.');
|
|
20
|
+
}
|
|
21
|
+
const message = `data: ${JSON.stringify(data)}\n${event ? `event: ${event}\n` : ''}id: ${Date.now()}\n\n`;
|
|
22
|
+
this.controller.enqueue(this.encoder.encode(message));
|
|
23
|
+
}
|
|
24
|
+
close() {
|
|
25
|
+
if (!this.controller) {
|
|
26
|
+
throw new Error('SSEConnection not initialized. Call initialize() first.');
|
|
27
|
+
}
|
|
28
|
+
this.controller.close();
|
|
29
|
+
}
|
|
30
|
+
getResponse() {
|
|
31
|
+
const stream = new ReadableStream({
|
|
32
|
+
start: (controller) => {
|
|
33
|
+
this.controller = controller;
|
|
34
|
+
if (this.resolveInitialize) {
|
|
35
|
+
this.resolveInitialize();
|
|
36
|
+
this.resolveInitialize = null;
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
return new NextResponse(stream, {
|
|
41
|
+
headers: {
|
|
42
|
+
'Content-Type': 'text/event-stream',
|
|
43
|
+
'Cache-Control': 'no-cache',
|
|
44
|
+
'Connection': 'keep-alive',
|
|
45
|
+
'X-Accel-Buffering': 'no',
|
|
46
|
+
'retry': this.config.reconnectInterval.toString(),
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function createSSEHandler(handler, config) {
|
|
52
|
+
return async () => {
|
|
53
|
+
const sse = new SSEConnection(config);
|
|
54
|
+
const response = sse.getResponse();
|
|
55
|
+
await sse.initialize();
|
|
56
|
+
handler(sse).catch((error) => {
|
|
57
|
+
console.error('SSE Handler Error:', error);
|
|
58
|
+
sse.close();
|
|
59
|
+
});
|
|
60
|
+
return response;
|
|
61
|
+
};
|
|
62
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "use-next-sse",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "A lightweight Server-Sent Events (SSE) library for Next.js",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsc",
|
|
9
|
+
"test": "jest",
|
|
10
|
+
"prepublishOnly": "npm run build"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"nextjs",
|
|
14
|
+
"sse",
|
|
15
|
+
"server-sent-events",
|
|
16
|
+
"react"
|
|
17
|
+
],
|
|
18
|
+
"author": "Alexander Kasten",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"next": ">13.0.0",
|
|
22
|
+
"react": ">=18.0.0",
|
|
23
|
+
"react-dom": ">=18.0.0"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
30
|
+
"@testing-library/react": "^16.0.0",
|
|
31
|
+
"@trivago/prettier-plugin-sort-imports": "^5.1.0",
|
|
32
|
+
"@types/jest": "^29.5.2",
|
|
33
|
+
"@types/node": "^14.0.0",
|
|
34
|
+
"@types/react": "^18.0.0",
|
|
35
|
+
"jest": "^29.5.0",
|
|
36
|
+
"prettier": "^3.4.2",
|
|
37
|
+
"react": "^18.2.0",
|
|
38
|
+
"react-dom": "^18.2.0",
|
|
39
|
+
"ts-jest": "^29.1.0",
|
|
40
|
+
"typescript": "^4.5.0"
|
|
41
|
+
},
|
|
42
|
+
"config": {
|
|
43
|
+
"sse": {
|
|
44
|
+
"reconnectInterval": 1000,
|
|
45
|
+
"maxReconnectAttempts": 5
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|