{"library":"sse.js","title":"sse.js: Flexible Server-Sent Events Client","type":"library","description":"sse.js is a robust JavaScript library designed as a flexible replacement for the standard `EventSource` API, enabling more control over Server-Sent Events (SSE) streams. Unlike `EventSource`, it supports POST requests and allows custom HTTP headers, making it suitable for authenticated or complex SSE integrations. The library is currently at version 2.8.0 and receives active maintenance, with recent releases focusing on spec compliance, type definition fixes, and enhanced auto-reconnect capabilities. It differentiates itself by providing a comprehensive EventSource polyfill that addresses the limitations of the native API, such as the inability to send payloads or custom headers, while offering features like configurable reconnection logic and exposure of HTTP response details.","language":"javascript","status":"active","last_verified":"Sat Apr 25","install":{"commands":["npm install sse.js"],"cli":null},"imports":["import { SSE } from 'sse.js';","import type { SSEOptions } from 'sse.js';","const { SSE } = require('sse.js');"],"auth":{"required":false,"env_vars":[]},"links":{"homepage":null,"github":"https://github.com/mpetazzoni/sse.js","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/sse.js","openapi_spec":null,"status_page":null,"smithery":null},"quickstart":{"code":"import { SSE } from 'sse.js';\n\nconst SSE_SERVER_URL = process.env.SSE_SERVER_URL ?? 'http://localhost:3000/events';\nconst AUTH_TOKEN = process.env.AUTH_TOKEN ?? 'your-secret-token';\n\ninterface MyEventData {\n  message: string;\n  timestamp: number;\n}\n\nasync function connectToSSE() {\n  const source = new SSE(SSE_SERVER_URL, {\n    headers: {\n      'Authorization': `Bearer ${AUTH_TOKEN}`,\n      'Accept': 'text/event-stream',\n    },\n    method: 'POST',\n    payload: JSON.stringify({ initialData: 'client-hello' }),\n    autoReconnect: true,\n    reconnectDelay: 5000,\n    maxRetries: 5,\n    useLastEventId: true, // Recommended for resuming streams\n    start: false, // Don't start streaming immediately\n  });\n\n  source.addEventListener('open', (event: Event) => {\n    const openEvent = event as Event & { responseCode?: number; headers?: Record<string, string[]> };\n    console.log(`SSE connection opened. HTTP Status: ${openEvent.responseCode}`);\n    if (openEvent.headers) {\n      console.log('Response Headers:', openEvent.headers);\n    }\n  });\n\n  source.addEventListener('message', (event: MessageEvent) => {\n    try {\n      const payload: MyEventData = JSON.parse(event.data);\n      console.log(`Received event (id: ${event.lastEventId}):`, payload.message, `at ${new Date(payload.timestamp).toLocaleTimeString()}`);\n    } catch (e) {\n      console.error('Failed to parse event data:', e, event.data);\n    }\n  });\n\n  source.addEventListener('error', (event: Event) => {\n    const errorEvent = event as Event & { responseCode?: number; message?: string };\n    console.error(`SSE connection error. HTTP Status: ${errorEvent.responseCode}, Message: ${errorEvent.message}`);\n    if (source.autoReconnect && source.retryCount < (source.maxRetries ?? Infinity)) {\n      console.log(`Attempting to reconnect in ${source.reconnectDelay}ms (attempt ${source.retryCount + 1}/${source.maxRetries ?? '∞'})...`);\n    } else if (source.autoReconnect && source.maxRetries && source.retryCount >= source.maxRetries) {\n      console.log('Max reconnection retries reached. Connection permanently closed.');\n    } else {\n      console.log('Connection closed or not configured for auto-reconnect.');\n    }\n  });\n\n  source.addEventListener('abort', () => {\n    console.log('SSE connection aborted by client.');\n  });\n\n  // Manually start the stream after setting up listeners\n  console.log('Starting SSE stream...');\n  source.stream();\n\n  // Example of closing the connection after some time\n  setTimeout(() => {\n    console.log('Closing SSE connection after 60 seconds...');\n    source.close();\n  }, 60000);\n}\n\nconnectToSSE();\n","lang":"typescript","description":"This quickstart demonstrates how to establish an SSE connection using `sse.js` with custom headers, POST requests, and robust auto-reconnect logic. It includes event listeners for 'open', 'message', 'error', and 'abort' events, showing how to handle incoming JSON data and reconnection attempts, all within a TypeScript context. The stream is manually started and closed after a timeout.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}