core-sse
v0.1.1
Published
Server-Sent Events package for Node.js/Express and React/Next.js.
Downloads
12
Maintainers
Readme
core-sse
Server-Sent Events (SSE) package for Node.js/Express (backend) and React/Next.js (frontend).
Features
- Express Middleware: Easily add SSE channels to your backend.
- React Hook: Subscribe to SSE channels in your frontend with
useSSE. - TypeScript Types: Shared types for both client and server usage.
- Heartbeat, Retry, Custom Events: Full support for SSE features.
Installation
npm install core-sseUsage
Backend (Express)
import { sseMiddleware, sseEmitter, emitSSEEvent } from 'core-sse';
// Add SSE endpoint
app.get('/events/:channel', sseMiddleware);
// Broadcast an event to all clients on a channel
sseEmitter.emit('broadcast', {
channel: 'user',
event: 'user-update',
data: { ...user },
});
// Or use emitSSEEvent directly
emitSSEEvent('user', 'user-update', { ...user });Frontend (React)
import { useSSE } from 'core-sse';
const { data, isConnected, error } = useSSE('user', {
baseUrl: 'http://localhost:4000', // or your production backend
heartbeat: true,
onMessage: (data) => { ... },
onEvent: {
'user-update': (data) => { ... },
},
onOpen: () => { ... },
onClose: () => { ... },
onError: (err) => { ... },
});API Reference
Server
sseMiddleware(req, res)— Express handler for SSE channels.sseEmitter— Node.js EventEmitter for broadcasting events.emitSSEEvent(channel, event, data)— Send a named event to all clients.emitSSEMessage(channel, data)— Send a default message to all clients.
Client
useSSE(channel, options)— React hook for subscribing to SSE channels.- Options:
baseUrl,heartbeat,retryDelay,maxRetryDelay,onMessage,onEvent,onOpen,onClose,onError.
TypeScript Support
- All exports are fully typed for both client and server usage.
License
MIT
