@silyze/next-sse
v1.0.0
Published
Server Sent Events implementation for @mojsoski/next-endpoint
Readme
Next SSE
Server-Sent Events implementation for @mojsoski/next-endpoint, providing a simple API to stream SSE responses in Next.js endpoints.
Installation
npm install @silyze/next-sseUsage
Import and use in your Next.js API route to create an SSE stream:
import createServerSentEvents from "@silyze/next-sse";
import { createApiEndpoint } from "@mojsoski/next-endpoint";
import { NextResponse } from "next/server";
export const GET = createApiEndpoint(({ request }) => {
return createServerSentEvents(
(write) => {
// Send a simple data message
void write({ data: "Hello, World!" });
// Optionally return a cleanup function
return () => {
// Clean up timers or subscriptions here
};
},
{
request,
Response: NextResponse,
keepAliveInterval: 1000, // milliseconds between comment pings
}
);
}, [] as const);API Reference
createServerSentEvents(handler, options)
Creates a streaming SSE response.
handler: ServerSentEventsHandlerFunction invoked with awritecallback to send SSE messages. May return a cleanup function.options: ServerSentEventsOptions<TRequest, TResponse>Either the incomingRequestobject or an object with:request: the incoming requestResponse: a response constructor (e.g.NextResponse)keepAliveInterval?: interval in milliseconds to send SSE comments (":"ping) to keep the connection alive (default:1000)
Returns an instance of Response (or the provided Response constructor) with headers:
Content-Type: text/event-streamCache-Control: no-cacheConnection: keep-alive
Types
ServerSentData
export type ServerSentData = {
data: string;
id?: string;
event?: string;
type?: "data" | undefined;
};- data: The message payload (string).
- id: Optional message identifier (
id:field). - event: Optional custom event type (
event:field). - type: Message type; normally omitted or set to
"data".
ServerSentComment
export type ServerSentComment = {
type: "comment";
text: string;
};- type:
"comment"to send an SSE comment. - text: Comment text; each line will be prefixed with
": ".
ServerSentRetry
export type ServerSentRetry = {
type: "retry";
time: number;
};- type:
"retry"to adjust reconnection time. - time: Milliseconds the client should wait before retrying.
ServerSentMessage
export type ServerSentMessage =
| ServerSentData
| ServerSentRetry
| ServerSentComment;Union of all supported message types.
ServerSentEventsWrite
export type ServerSentEventsWrite = (
message: ServerSentMessage
) => Promise<void>;Function to send a single SSE message.
ServerSentEventsHandler
export type ServerSentEventsHandler = (
write: ServerSentEventsWrite
) => (() => void) | void;Function that receives the write callback. Can return an optional cleanup function that is called when the connection is closed or aborted.
ServerSentEventsOptions<TRequest, TResponse>
export type ServerSentEventsOptions<
TRequest extends Request,
TResponse extends Response
> =
| TRequest
| {
request: TRequest;
Response: new (body?: BodyInit | null, init?: ResponseInit) => TResponse;
keepAliveInterval?: number;
};Options to configure the SSE stream:
- Pass the raw
Requestif using standard web APIs. - Or supply an object with
request, a customResponseconstructor, and optionalkeepAliveInterval.
Examples
Custom Event and ID
return createServerSentEvents((write) => {
void write({
data: JSON.stringify({ count: 1 }),
id: "1",
event: "tick",
});
});Retry Directive
return createServerSentEvents((write) => {
// Instruct client to retry after 5 seconds on disconnect
void write({ type: "retry", time: 5000 });
});Comments for Keep-Alive
return createServerSentEvents((write) => {
// Send a comment ping manually
void write({ type: "comment", text: "heartbeat" });
});