https://github.com/neo-ciber94/next-sse
A mechanism for serve and read server-sent-events
https://github.com/neo-ciber94/next-sse
Last synced: 6 months ago
JSON representation
A mechanism for serve and read server-sent-events
- Host: GitHub
- URL: https://github.com/neo-ciber94/next-sse
- Owner: Neo-Ciber94
- License: mit
- Created: 2023-11-05T20:07:35.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-11-15T03:13:43.000Z (almost 2 years ago)
- Last Synced: 2025-04-13T06:17:26.140Z (6 months ago)
- Language: TypeScript
- Size: 75.2 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# next-sse
Provides a mechanism for managing `server sent events` in NextJS.
## Installation
```bash
# npm
npm install next-sse zod
``````bash
# yarn
yarn add next-sse zod
``````bash
# pnpm
pnpm add next-sse zod
```## Usage
Declare the stream on your server
```ts
// /app/api/counter/route.tsimport { createSource } from "next-sse/server";
import { z } from "zod";const delay = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));const counter = createSource("/api/counter")
.input(z.number())
.onSubscribe(({ input, emit }) => {
for (let i = 0; i < input; i++) {
emit(i);
await delay(1000);
}
});export type CounterStream = typeof counter;
```In your client consume your stream with `useStream()`.
```tsx
// app/page.tsximport { createClient } from "next-sse/client";
import type { CounterStream } from "@/app/api/counter/route";const client = createClient("/api/counter");
export default function Page() {
const [count, setCount] = useState(0);
const { subscribe, isStreaming, error } = client.useStream();useEffect(() => {
subscribe({
input: 10,
onData(data) {
setCount(data);
},
});
}, [subscribe]);return
{ count };
}
```Or using `stream()`.
```ts
export default function Page() {
const [count, setCount] = useState(0);useEffect(() => {
const run = async () => {
for await (const x of client.stream({ input: 10 })) {
setCount(x);
}
};run();
}, []);return
{ count };
}
```