Server-Sent Events (SSE) client for Node.js and browsers with automatic reconnection.
npm install @neabyte/sse-client
<script type="module"> import sseClient from 'https://cdn.jsdelivr.net/npm/@neabyte/sse-client/+esm' const client = sseClient('https://api.example.com/events', (message) => { console.log('SSE Response:', message) }) </script>
// ESM import sseClient from '@neabyte/sse-client' // CommonJS const sseClient = require('@neabyte/sse-client') // Simple connection with message callback const client = sseClient('https://api.example.com/events', (message) => { console.log('SSE Response:', message) })
import sseClient, { type SSEConfig, SSEClient } from '@neabyte/sse-client' // Configuration with custom settings const config: SSEConfig = { headers: { 'Authorization': 'Bearer your-token', 'X-Custom-Header': 'value' }, retryInterval: 5000, // Retry every 5 seconds (default: 3000) retryAttempts: 10, // Try up to 10 times (default: 3) autoReconnect: true, // Enable auto-reconnection (default: true) timeout: 30000 // 30 second connection timeout (default: 30000) } // Create client with configuration const client: SSEClient = sseClient('https://api.example.com/events', (message: unknown) => { console.log('SSE Response', message) }, config) // Listen for connection status changes client.on('callback', (data) => { console.log('SSE Callback:', data) })
sseClient(url, callback, config?)
url<string>: The SSE endpoint URL to connect to.callback<function>: Function to handle incoming messages.message<SSEMessage>: The received SSE message object.
config<SSEConfig>: (Optional) Configuration options for the client.headers<Record<string, string>>: (Optional) Custom headers to send with the request.retryInterval<number>: (Optional) Retry interval in milliseconds. Defaults to 3000.retryAttempts<number>: (Optional) Maximum number of retry attempts. Defaults to 3.autoReconnect<boolean>: (Optional) Enable automatic reconnection. Defaults to true.timeout<number>: (Optional) Connection timeout in milliseconds. Defaults to 30000.
- Returns:
SSEClient - Description: Factory function that creates and connects an SSE client with automatic reconnection.
client.connect()
- Returns:
Promise<void> - Description: Establishes connection to the SSE endpoint with retry logic and error handling.
client.disconnect()
- Returns:
void - Description: Disconnects from the SSE endpoint and cleans up resources.
client.on('callback', (status) => {})
status<object>: Connection status information.name<ConnectionStatus>: Current connection status. Possible values:'connecting'- Initial connection attempt'connected'- Successfully connected and streaming'disconnected'- Connection closed (normal or error)'reconnecting'- Attempting to reconnect after failure'error'- Connection failed with error
message<string | null>: Optional status message.
- Description: Emitted when connection status changes.
This project is licensed under the MIT License - see the LICENSE file for details.