### Initialize SSE Connection Source: https://context7.com/mpetazzoni/sse.js/llms.txt Create a new SSE connection. By default, the request starts immediately. Pass `start: false` to defer until `.stream()` is called. The HTTP method defaults to `GET`; providing a `payload` automatically switches to `POST`. ```javascript import { SSE } from "./sse.js"; // Minimal GET stream — starts immediately const source = new SSE("https://api.example.com/events"); // Deferred POST stream with auth header and JSON body const source = new SSE("https://api.example.com/stream", { start: false, method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9...", }, payload: JSON.stringify({ filter: "temperature > 25", limit: 100 }), withCredentials: false, debug: false, }); // Use as a drop-in EventSource polyfill EventSource = SSE; const native = new EventSource("https://api.example.com/events"); ``` -------------------------------- ### SSE Constructor Source: https://context7.com/mpetazzoni/sse.js/llms.txt Creates a new SSE connection. The request can start immediately or be deferred. The HTTP method defaults to GET, but automatically switches to POST if a payload is provided. ```APIDOC ## Constructor: `new SSE(url, options)` Creates a new SSE connection. By default the request starts immediately. Pass `start: false` to defer until `.stream()` is called. The HTTP method defaults to `GET`; providing a `payload` automatically switches to `POST`. ### Parameters - **url** (string) - The URL to connect to. - **options** (object) - Optional configuration for the connection. - **headers** (object) - HTTP request headers. Defaults to `{}`. - **payload** (string|Blob|FormData|…) - Request body; triggers POST automatically. Defaults to `""`. - **method** (string) - Override HTTP method. Defaults to `"GET"` or `"POST"` based on `payload`. - **withCredentials** (boolean) - Send cookies (CORS credentials `include`). Defaults to `false`. - **start** (boolean) - Auto-start stream on construction. Defaults to `true`. - **debug** (boolean) - Log raw chunks and events to console. Defaults to `false`. - **autoReconnect** (boolean) - Automatically reconnect on error/close. Defaults to `false`. - **reconnectDelay** (number) - Milliseconds between reconnection attempts. Defaults to `3000`. - **maxRetries** (number|null) - Max reconnect attempts; `null` = unlimited. Defaults to `null`. - **useLastEventId** (boolean) - Send `Last-Event-ID` header on reconnect. Defaults to `true`. ### Request Example ```js import { SSE } from "./sse.js"; // Minimal GET stream — starts immediately const source = new SSE("https://api.example.com/events"); // Deferred POST stream with auth header and JSON body const source = new SSE("https://api.example.com/stream", { start: false, method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9...", }, payload: JSON.stringify({ filter: "temperature > 25", limit: 100 }), withCredentials: false, debug: false, }); // Use as a drop-in EventSource polyfill EventSource = SSE; const native = new EventSource("https://api.example.com/events"); ``` ``` -------------------------------- ### SSE Server Response Format Example Source: https://context7.com/mpetazzoni/sse.js/llms.txt Provides an example of the standard SSE wire format, including comments, named events, multi-line data, event IDs, and retry delays. This format is handled by sse.js. ```text # Comment lines (colon-prefixed) are silently ignored : keep-alive ping # Minimal event (default type "message") data: Hello, world! # Named event type event: alert data: {"level":"critical","msg":"Disk full"} # Multi-line data — lines are joined with \n data: line one data: line two data: line three # Event with ID and server-requested retry delay id: evt-42 retry: 5000 event: update data: {"temp":23.4,"unit":"C"} # Each event is terminated by a blank line ``` -------------------------------- ### Example: Full Last-Event-ID Handling with SSE.js Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Demonstrates a complete setup for SSE.js with auto-reconnect and Last-Event-ID support. It includes event listeners for 'message' and 'open' to log received event IDs and reconnection status. ```javascript const source = new SSE("/api/events", { autoReconnect: true, useLastEventId: true, headers: { "Client-ID": "dashboard-1" }, }); source.addEventListener("message", (e) => { if (e.id) { console.log(`Received event ${e.id}`); // The lastEventId is automatically tracked // and will be sent on next reconnection } }); source.addEventListener("open", (e) => { if (source.lastEventId) { console.log(`Reconnected, resuming from event ${source.lastEventId}`); } }); ``` -------------------------------- ### Manually Start SSE Stream Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Initialize SSE with 'start: false' to manually control stream activation using the stream() method. ```javascript var source = new SSE(url, {start: false}); source.addEventListener('message', (e) => { ... }); // ... later on source.stream(); ``` -------------------------------- ### source.stream() Source: https://context7.com/mpetazzoni/sse.js/llms.txt Initiates or re-initiates the HTTP request and begins reading the event stream. This method is required when `start: false` was passed to the constructor. ```APIDOC ## `source.stream()` Initiates (or re-initiates) the HTTP request and begins reading the event stream. Does nothing if a connection is already open. Required when `start: false` was passed to the constructor. ### Method `source.stream()` ### Description Starts the SSE connection and begins processing events. Useful for manually controlling the stream's lifecycle, especially when `start: false` is used during initialization. ### Event Listeners - **`open`**: Fired when the connection is established. The event object contains `responseCode` and `headers`. - **`message`**: Fired when a standard `message` event is received. The event data is in `e.data`. - **`error`**: Fired when an error occurs. The event object contains `responseCode` and `data`. ### Request Example ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/events", { start: false }); source.addEventListener("message", (e) => { const payload = JSON.parse(e.data); console.log("Received:", payload); // e.id → event ID (or null) // e.lastEventId → last seen event ID // e.source → the SSE instance }); source.addEventListener("open", (e) => { console.log("Connected — HTTP", e.responseCode); console.log("Content-Type:", e.headers["content-type"]); }); source.addEventListener("error", (e) => { console.error("Stream error — HTTP", e.responseCode, e.data); }); // Start the stream explicitly source.stream(); // source.readyState → SSE.CONNECTING (0) immediately // source.readyState → SSE.OPEN (1) after headers received ``` ``` -------------------------------- ### Initiate SSE Stream Source: https://context7.com/mpetazzoni/sse.js/llms.txt Initiates (or re-initiates) the HTTP request and begins reading the event stream. Required when `start: false` was passed to the constructor. Listeners can be attached for 'message', 'open', and 'error' events. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/events", { start: false }); source.addEventListener("message", (e) => { const payload = JSON.parse(e.data); console.log("Received:", payload); // e.id → event ID (or null) // e.lastEventId → last seen event ID // e.source → the SSE instance }); source.addEventListener("open", (e) => { console.log("Connected — HTTP", e.responseCode); console.log("Content-Type:", e.headers["content-type"]); }); source.addEventListener("error", (e) => { console.error("Stream error — HTTP", e.responseCode, e.data); }); // Start the stream explicitly source.stream(); // source.readyState → SSE.CONNECTING (0) immediately // source.readyState → SSE.OPEN (1) after headers received ``` -------------------------------- ### SSE with Custom HTTP Method Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Override the default HTTP method (e.g., to GET) even when a payload is provided. ```javascript var source = new SSE(url, { headers: { "Content-Type": "text/plain" }, payload: "Hello, world!", method: "GET", }); ``` -------------------------------- ### SSE ReadyState Constants and Usage Source: https://context7.com/mpetazzoni/sse.js/llms.txt Demonstrates the use of SSE ready state constants (INITIALIZING, CONNECTING, OPEN, CLOSED) and how to interact with the SSE instance to stream data and monitor its state. ```javascript import { SSE } from "./sse.js"; console.log(SSE.INITIALIZING); // -1 — constructed with start:false, not yet streaming console.log(SSE.CONNECTING); // 0 — stream() called, waiting for response headers console.log(SSE.OPEN); // 1 — headers received, actively streaming console.log(SSE.CLOSED); // 2 — connection ended (normally, by error, or close()) const source = new SSE("https://api.example.com/events", { start: false }); console.log(source.readyState); // -1 source.stream(); console.log(source.readyState); // 0 source.addEventListener("open", () => { console.log(source.readyState); // 1 }); ``` -------------------------------- ### Instantiate SSE with URL Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Create a new SSE instance with a given URL. ```javascript var source = new SSE(url, options); ``` -------------------------------- ### Initialize SSE Connection and Event Listeners Source: https://github.com/mpetazzoni/sse.js/blob/main/demo.html Sets up the SSE connection with configurable options and attaches event listeners for 'message', 'open', and 'error'. The 'error' handler includes logic for retries and connection closing. ```javascript import { SSE } from "./lib/sse.js"; var url = document.getElementById("url"); var button = document.getElementById("go"); var content = document.getElementById("content"); var autoReconnect = document.getElementById("auto-reconnect"); var reconnectDelay = document.getElementById("reconnect-delay"); var useLastEventId = document.getElementById("use-last-event-id"); var maxRetries = document.getElementById("max-retries"); var source; function addMessage(data, type = "") { var el = document.createElement("div"); if (type) { el.className = type; } var span = document.createElement("span"); span.appendChild(document.createTextNode(new Date().toString())); el.appendChild(span); var pre = document.createElement("pre"); pre.appendChild( document.createTextNode( typeof data === "object" ? JSON.stringify(data, null, 2) : String(data) ) ); el.appendChild(pre); content.append(el); } function show(e) { console.log("Received SSE message:", e); let data = e.data; try { if ( typeof data === "string" && (data.startsWith("{ ") || data.startsWith("[")) ) { data = JSON.parse(data); if (data.time && typeof data.time === "number") { data.time = new Date(data.time * 1000); } } } catch (err) { console.warn("Failed to parse message data as JSON:", err); } addMessage(data); } function start() { if (!url.value) { addMessage("Please enter a valid SSE URL", "error"); return; } content.innerHTML = ""; addMessage("Connecting to " + url.value, "info"); const options = { start: false, debug: true, autoReconnect: autoReconnect.checked, reconnectDelay: parseInt(reconnectDelay.value, 10), useLastEventId: useLastEventId.checked, maxRetries: maxRetries.value ? parseInt(maxRetries.value, 10) : null, }; if (options.autoReconnect) { const retryMsg = options.maxRetries ? `Auto-reconnect enabled (${options.reconnectDelay}ms delay, max ${options.maxRetries} retries)` : `Auto-reconnect enabled (${options.reconnectDelay}ms delay, unlimited retries)` addMessage(retryMsg, "info"); } source = new SSE(url.value, options); source.addEventListener("message", show); source.addEventListener("open", function (e) { addMessage("Connection opened", "info"); }); source.addEventListener("error", (e) => { const msg = e.data ? `Error: ${e.data}` : "Error: Unknown error occurred"; addMessage(msg, "error"); const nextAttempt = source.retryCount + 1; if (source.maxRetries && nextAttempt > source.maxRetries) { // Max retries reached, reset button button.value = "Start"; button.onclick = start; addMessage( `Max retries (${source.maxRetries}) reached, connection permanently closed`, "info" ); } else if (!source.autoReconnect) { // No auto-reconnect, reset button button.value = "Start"; button.onclick = start; } else { // Still retrying addMessage( `Will attempt to reconnect in ${ options.reconnectDelay }ms (attempt ${nextAttempt}${ source.maxRetries ? "/" + source.maxRetries : "" })`, "info" ); } }); source.stream(); button.value = "Stop"; button.onclick = reset; } function reset() { if (source) { source.close(); addMessage("Connection closed", "info"); } button.value = "Start"; button.onclick = start; } reset(); ``` -------------------------------- ### Release SSE.js Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Commands to version, tag, and publish the sse.js library to GitHub and NPM. Ensure to create a new GitHub release after publishing. ```bash $ npm version {major,minor,patch} $ git publish --tags $ npm publish --otp ``` -------------------------------- ### Use SSE as EventSource Polyfill Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Replace the global EventSource with SSE for seamless integration if needed. ```javascript EventSource = SSE; ``` -------------------------------- ### Import SSE from Module Context Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Import the SSE class when using a module system. ```javascript import { SSE } from "./sse.js"; ``` -------------------------------- ### Basic SSE Usage with Message Listener Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Connect to an SSE stream, parse JSON data, and log it to the console. ```javascript var source = new SSE(url); source.addEventListener("message", function (e) { // Assuming we receive JSON-encoded data payloads: var payload = JSON.parse(e.data); console.log(payload); }); ``` -------------------------------- ### Handle Open Event with Headers and Status Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Listen for the 'open' event to access response headers and the HTTP status code when the SSE stream connects. The headers are provided as a map of lowercased header names to an array of values. ```javascript var source = new SSE(url); source.addEventListener("open", function (e) { console.log( "Got a " + e.responseCode + " response with headers: " + e.headers ); }); source.stream(); ``` -------------------------------- ### SSE with POST Request and Payload Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Make a POST request with a specified Content-Type and payload. ```javascript var source = new SSE(url, { headers: { "Content-Type": "text/plain" }, payload: "Hello, world!", }); ``` -------------------------------- ### Import SSE from Non-Module Context Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Dynamically import SSE and assign it to the window object in non-module environments. ```javascript (async () => { const { SSE } = import("./sse.js"); window.SSE = SSE; })(); ``` -------------------------------- ### TypeScript Usage with SSE Options Source: https://context7.com/mpetazzoni/sse.js/llms.txt Shows how to use sse.js with TypeScript, including defining SSEOptions for headers, payload, auto-reconnect, and last event ID. Also demonstrates event listeners for 'message', 'readystatechange', and 'error'. ```typescript import { SSE, SSEOptions, SSEvent, ReadyStateEvent } from "./sse.js"; const options: SSEOptions = { headers: { Authorization: "Bearer token123" }, payload: JSON.stringify({ query: "SELECT * FROM sensors LIMIT 10" }), autoReconnect: true, reconnectDelay: 3000, maxRetries: 5, useLastEventId: true, }; const source: SSE = new SSE("https://api.example.com/query-stream", options); source.addEventListener("message", (e: SSEvent) => { const row = JSON.parse(e.data) as { id: number; value: number }; console.log(row.id, row.value); }); source.addEventListener("readystatechange", (e: ReadyStateEvent) => { console.log("readyState:", e.readyState); }); source.addEventListener("error", (e: SSEvent) => { console.error("HTTP", e.responseCode, e.data); }); ``` -------------------------------- ### SSE ReadyState Constants Source: https://context7.com/mpetazzoni/sse.js/llms.txt The SSE class exposes constants that mirror the EventSource spec, along with an INITIALIZING state for pre-connection. ```APIDOC ## SSE ReadyState Constants `SSE` exposes four state constants mirroring the `EventSource` spec, plus an `INITIALIZING` pre-connection state. ```js import { SSE } from "./sse.js"; console.log(SSE.INITIALIZING); // -1 — constructed with start:false, not yet streaming console.log(SSE.CONNECTING); // 0 — stream() called, waiting for response headers console.log(SSE.OPEN); // 1 — headers received, actively streaming console.log(SSE.CLOSED); // 2 — connection ended (normally, by error, or close()) const source = new SSE("https://api.example.com/events", { start: false }); console.log(source.readyState); // -1 source.stream(); console.log(source.readyState); // 0 source.addEventListener("open", () => { console.log(source.readyState); // 1 }); ``` ``` -------------------------------- ### Client-side Handler for SSE 'update' Event Source: https://context7.com/mpetazzoni/sse.js/llms.txt Demonstrates how to handle a specific SSE event ('update') on the client-side using sse.js, including parsing JSON data, accessing the event ID, and checking the reconnect delay. ```javascript // Corresponding client-side handler source.addEventListener("update", (e) => { const { temp, unit } = JSON.parse(e.data); console.log(`${temp} °${unit}`); // "23.4 °C" console.log("Event ID:", e.id); // "evt-42" console.log("Reconnect delay:", source.reconnectDelay); // 5000 (ms) }); ``` -------------------------------- ### SSE with Custom Headers Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Pass custom HTTP headers, such as Authorization, during SSE connection. ```javascript var source = new SSE(url, { headers: { Authorization: "Bearer 0xdeadbeef" } }); ``` -------------------------------- ### SSE with Auto-Reconnect Configuration Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Configure SSE to automatically reconnect on connection loss with customizable delay and retry limits. Sending Last-Event-ID on reconnect is recommended. ```javascript var source = new SSE(url, { autoReconnect: true, // Enable auto-reconnect reconnectDelay: 3000, // Wait 3 seconds before reconnecting maxRetries: null, // Retry indefinitely (set a number to limit retries) useLastEventId: true, // Send Last-Event-ID header on reconnect (recommended) }); ``` -------------------------------- ### Server Response Format Source: https://context7.com/mpetazzoni/sse.js/llms.txt The server must emit events in the standard SSE wire format. sse.js handles various line endings, BOM stripping, comments, multi-line data, and retry overrides. ```APIDOC ## Server Response Format The server must emit events in the standard SSE wire format as defined by the WHATWG spec. `sse.js` handles all three line-ending styles (`\n`, `\r`, `\r\n`), BOM stripping, comment lines, multi-line data concatenation, and server-specified `retry` overrides. ``` # Comment lines (colon-prefixed) are silently ignored : keep-alive ping # Minimal event (default type "message") data: Hello, world! # Named event type event: alert data: {"level":"critical","msg":"Disk full"} # Multi-line data — lines are joined with \n data: line one data: line two data: line three # Event with ID and server-requested retry delay id: evt-42 retry: 5000 event: update data: {"temp":23.4,"unit":"C"} # Each event is terminated by a blank line ``` ```js // Corresponding client-side handler source.addEventListener("update", (e) => { const { temp, unit } = JSON.parse(e.data); console.log(`${temp} °${unit}`); // "23.4 °C" console.log("Event ID:", e.id); // "evt-42" console.log("Reconnect delay:", source.reconnectDelay); // 5000 (ms) }); ``` ``` -------------------------------- ### TypeScript Usage Source: https://context7.com/mpetazzoni/sse.js/llms.txt sse.js provides full TypeScript type definitions for enhanced development experience. ```APIDOC ## TypeScript Usage `sse.js` ships with full TypeScript type definitions in `types/sse.d.ts`. ```ts import { SSE, SSEOptions, SSEvent, ReadyStateEvent } from "./sse.js"; const options: SSEOptions = { headers: { Authorization: "Bearer token123" }, payload: JSON.stringify({ query: "SELECT * FROM sensors LIMIT 10" }), autoReconnect: true, reconnectDelay: 3000, maxRetries: 5, useLastEventId: true, }; const source: SSE = new SSE("https://api.example.com/query-stream", options); source.addEventListener("message", (e: SSEvent) => { const row = JSON.parse(e.data) as { id: number; value: number }; console.log(row.id, row.value); }); source.addEventListener("readystatechange", (e: ReadyStateEvent) => { console.log("readyState:", e.readyState); }); source.addEventListener("error", (e: SSEvent) => { console.error("HTTP", e.responseCode, e.data); }); ``` ``` -------------------------------- ### source.close() Source: https://context7.com/mpetazzoni/sse.js/llms.txt Closes the active XHR connection, cancels any pending reconnect timer, and permanently disables autoReconnect. Fires an `abort` event then transitions `readyState` to `CLOSED`. ```APIDOC ## `source.close()` Closes the active XHR connection, cancels any pending reconnect timer, and permanently disables `autoReconnect`. Fires an `abort` event then transitions `readyState` to `CLOSED`. ### Method `source.close()` ### Description Gracefully terminates the Server-Sent Events connection. This action prevents any further automatic reconnections if `autoReconnect` was enabled. ### Event Listeners - **`abort`**: Fired when `close()` is called, indicating the connection has been terminated. ### Request Example ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/live-feed", { autoReconnect: true, reconnectDelay: 2000, }); source.addEventListener("message", (e) => { const msg = JSON.parse(e.data); if (msg.type === "DONE") { // Permanently close; auto-reconnect will NOT fire source.close(); console.log("Stream closed by application."); } }); source.addEventListener("abort", () => { // Fired when close() is called console.log("Connection aborted. readyState:", source.readyState); // 2 }); ``` ``` -------------------------------- ### source.dispatchEvent(event) Source: https://context7.com/mpetazzoni/sse.js/llms.txt Dispatches a `CustomEvent` through the SSE instance's listener registry. Called internally for every parsed SSE chunk, `open`, `error`, `abort`, and `readystatechange` events. Returns `false` if `event.preventDefault()` was called by any handler, `true` otherwise. ```APIDOC ## `source.dispatchEvent(event)` Dispatches a `CustomEvent` through the SSE instance's listener registry. Called internally for every parsed SSE chunk, `open`, `error`, `abort`, and `readystatechange` events. Returns `false` if `event.preventDefault()` was called by any handler, `true` otherwise. ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/events", { start: false }); source.addEventListener("ping", (e) => { console.log("Ping received:", e.data); }); // Manually fire a synthetic event (useful in tests or for local simulation) const pingEvent = new CustomEvent("ping"); pingEvent.data = '{"ts": 1700000000}'; pingEvent.id = "synth-1"; const propagated = source.dispatchEvent(pingEvent); console.log("Event propagated:", propagated); // true ``` ``` -------------------------------- ### SSE Event Object Properties and Parsing Source: https://context7.com/mpetazzoni/sse.js/llms.txt Illustrates the properties of a CustomEvent dispatched by sse.js, including data, ID, lastEventId, source, and timeStamp. Shows how to parse JSON payloads and handle 'open', 'error', and 'message' events. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/feed"); source.addEventListener("message", (e) => { console.log(e.type); // "message" (or custom event name) console.log(e.data); // raw string payload (unparsed) console.log(e.id); // event ID from "id:" field, or null console.log(e.lastEventId); // last seen event ID (survives events without IDs) console.log(e.source); // reference to the SSE instance console.log(e.timeStamp); // UNIX ms timestamp of reception // Parse JSON payloads: try { const obj = JSON.parse(e.data); console.log(obj.temperature); // 42.7 } catch { console.warn("Non-JSON data:", e.data); } }); // "open" event — fires once when response headers arrive source.addEventListener("open", (e) => { console.log(e.responseCode); // 200 console.log(e.headers); // { "content-type": ["text/event-stream"], … } }); // "error" event — HTTP error or network failure source.addEventListener("error", (e) => { console.error(e.responseCode, e.data); // e.g. 401, "Unauthorized" }); ``` -------------------------------- ### Configure Auto-Reconnect for SSE Streams Source: https://context7.com/mpetazzoni/sse.js/llms.txt Enable automatic reconnection on connection drops or errors by setting `autoReconnect: true`. Configure retry delays, maximum retries, and whether to use the last event ID for resuming the stream. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/stream", { autoReconnect: true, reconnectDelay: 5000, // 5 s between attempts maxRetries: 10, // give up after 10 consecutive failures useLastEventId: true, // resume from last received event ID }); source.addEventListener("message", (e) => { console.log(`[${e.lastEventId}]`, JSON.parse(e.data)); }); source.addEventListener("open", (e) => { if (source.lastEventId) { console.log("Reconnected — resuming from event", source.lastEventId); } // retryCount resets to 0 here internally }); source.addEventListener("error", (e) => { if (source.maxRetries && source.retryCount >= source.maxRetries) { console.error("Max retries reached — giving up."); // autoReconnect is now false; connection is permanently closed } else if (source.autoReconnect) { console.warn( `Attempt ${source.retryCount + 1}/${source.maxRetries ?? "∞"} ` + `in ${source.reconnectDelay}ms…` ); } }); ``` -------------------------------- ### SSE Manual Reconnection on Error Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Handle connection errors manually by attempting to reconnect after a delay using source.stream(). ```javascript const source = new SSE(url, { autoReconnect: false }); source.addEventListener("error", (e) => { console.log("Connection lost"); // Wait a bit then reconnect setTimeout(() => { source.stream(); }, 3000); }); // Or reconnect on abort source.addEventListener("abort", () => { source.stream(); }); ``` -------------------------------- ### Listen for Specific Event Types Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Register a listener for a specific event type, such as 'status', to handle custom events dispatched by the server. The default event type is 'message'. ```javascript var source = new SSE(url); source.addEventListener("status", function (e) { console.log("System status is now: " + e.data); }); source.stream(); ``` -------------------------------- ### SSE Automatic Reconnection with Error Handling Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Implement automatic reconnection with a maximum number of retries and log connection status. ```javascript const source = new SSE(url, { autoReconnect: true, reconnectDelay: 3000, maxRetries: 5, // Stop after 5 failed attempts }); source.addEventListener("error", (e) => { if (source.maxRetries && source.retryCount >= source.maxRetries) { console.log("Max retries reached, connection permanently closed"); } else { console.log( `Connection lost. ${source.maxRetries ? `Attempt ${source.retryCount + 1}/${source.maxRetries}` : "Will"} reconnect in 3s...` ); } }); ``` -------------------------------- ### Handle Specific Event Types with on Style Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Alternatively, use the 'on' style to register event listeners for specific event types. This handler is called before any 'addEventListener' callbacks for the same event. ```javascript var source = new SSE(url); source.onstatus = function(e) { ... }; ``` -------------------------------- ### Configure SSE Auto-Reconnect Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Enable and configure automatic reconnection for SSE connections. Set delay, maximum retries, and whether to use the last event ID to resume the stream. The error event listener provides feedback on retry attempts. ```javascript const source = new SSE("/events", { autoReconnect: true, // Enable automatic reconnection reconnectDelay: 5000, // Wait 5 seconds between attempts maxRetries: 3, // Only try 3 times before giving up useLastEventId: true // Send Last-Event-ID to resume stream }); source.addEventListener("error", () => { if (source.maxRetries && source.retryCount >= source.maxRetries) { console.log("Max retries reached, connection permanently closed"); } else if (source.autoReconnect) { console.log(`Connection lost, will retry in ${source.reconnectDelay}ms`); console.log(`Attempt ${source.retryCount + 1}${source.maxRetries ? '/' + source.maxRetries : ''}`); } }); ``` -------------------------------- ### Register and Remove SSE Event Listeners Source: https://context7.com/mpetazzoni/sse.js/llms.txt Use `addEventListener` to handle specific SSE event types like 'message', 'alert', or 'status'. The `on` shorthand is also supported and called first. Listeners can be removed using `removeEventListener`. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/notifications"); // Standard message handler const onMessage = (e) => console.log("message:", e.data); source.addEventListener("message", onMessage); // Named event types from the server's "event:" field source.addEventListener("alert", (e) => console.warn("ALERT:", e.data)); source.addEventListener("status", (e) => console.info("STATUS:", e.data)); // on shorthand (called before addEventListener handlers) source.onstatus = (e) => console.log("Quick status:", e.data); // readystatechange events source.addEventListener("readystatechange", (e) => { const states = { "-1": "INITIALIZING", 0: "CONNECTING", 1: "OPEN", 2: "CLOSED" }; console.log("State →", states[e.readyState]); }); // Remove a listener later setTimeout(() => { source.removeEventListener("message", onMessage); console.log("message listener removed"); }, 30_000); ``` -------------------------------- ### Dispatch Custom SSE Events Source: https://context7.com/mpetazzoni/sse.js/llms.txt Manually dispatch `CustomEvent`s using `dispatchEvent` for testing or local simulation. This method is also used internally to propagate parsed SSE chunks and connection events. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/events", { start: false }); source.addEventListener("ping", (e) => { console.log("Ping received:", e.data); }); // Manually fire a synthetic event (useful in tests or for local simulation) const pingEvent = new CustomEvent("ping"); pingEvent.data = '{"ts": 1700000000}'; pingEvent.id = "synth-1"; const propagated = source.dispatchEvent(pingEvent); console.log("Event propagated:", propagated); // true ``` -------------------------------- ### source.addEventListener(type, listener) / source.removeEventListener(type, listener) Source: https://context7.com/mpetazzoni/sse.js/llms.txt Registers or unregisters a listener for any SSE event type. The `type` maps directly to the SSE `event:` field; the default type when no `event:` field is set is "message". The `on` shorthand property is also supported and is always called first. ```APIDOC ## `source.addEventListener(type, listener)` / `source.removeEventListener(type, listener)` Registers or unregisters a listener for any SSE event type. The `type` maps directly to the SSE `event:` field; the default type when no `event:` field is set is `"message"`. The `on` shorthand property is also supported and is always called first. ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/notifications"); // Standard message handler const onMessage = (e) => console.log("message:", e.data); source.addEventListener("message", onMessage); // Named event types from the server's "event:" field source.addEventListener("alert", (e) => console.warn("ALERT:", e.data)); source.addEventListener("status", (e) => console.info("STATUS:", e.data)); // on shorthand (called before addEventListener handlers) source.onstatus = (e) => console.log("Quick status:", e.data); // readystatechange events source.addEventListener("readystatechange", (e) => { const states = { "-1": "INITIALIZING", 0: "CONNECTING", 1: "OPEN", 2: "CLOSED" }; console.log("State →", states[e.readyState]); }); // Remove a listener later setTimeout(() => { source.removeEventListener("message", onMessage); console.log("message listener removed"); }, 30000); ``` ``` -------------------------------- ### SSE Event Object Properties Source: https://context7.com/mpetazzoni/sse.js/llms.txt Each event dispatched by sse.js is a CustomEvent with additional SSE-specific fields. ```APIDOC ## SSE Event Object Properties Every event dispatched by `sse.js` is a `CustomEvent` augmented with SSE-specific fields. ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/feed"); source.addEventListener("message", (e) => { console.log(e.type); // "message" (or custom event name) console.log(e.data); // raw string payload (unparsed) console.log(e.id); // event ID from "id:" field, or null console.log(e.lastEventId); // last seen event ID (survives events without IDs) console.log(e.source); // reference to the SSE instance console.log(e.timeStamp); // UNIX ms timestamp of reception // Parse JSON payloads: try { const obj = JSON.parse(e.data); console.log(obj.temperature); // 42.7 } catch { console.warn("Non-JSON data:", e.data); } }); // "open" event — fires once when response headers arrive source.addEventListener("open", (e) => { console.log(e.responseCode); // 200 console.log(e.headers); // { "content-type": ["text/event-stream"], … } }); // "error" event — HTTP error or network failure source.addEventListener("error", (e) => { console.error(e.responseCode, e.data); // e.g. 401, "Unauthorized" }); ``` ``` -------------------------------- ### Close SSE Connection Source: https://context7.com/mpetazzoni/sse.js/llms.txt Closes the active XHR connection, cancels any pending reconnect timer, and permanently disables `autoReconnect`. Fires an `abort` event then transitions `readyState` to `CLOSED`. Useful for stopping streams when a specific condition is met, like receiving a 'DONE' message. ```javascript import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/live-feed", { autoReconnect: true, reconnectDelay: 2000, }); source.addEventListener("message", (e) => { const msg = JSON.parse(e.data); if (msg.type === "DONE") { // Permanently close; auto-reconnect will NOT fire source.close(); console.log("Stream closed by application."); } }); source.addEventListener("abort", () => { // Fired when close() is called console.log("Connection aborted. readyState:", source.readyState); // 2 }); ``` -------------------------------- ### Manage Last-Event-ID for Stream Resumption Source: https://context7.com/mpetazzoni/sse.js/llms.txt Ensure stream continuity by enabling `useLastEventId` (default `true`). The library automatically tracks and sends the `Last-Event-ID` header on reconnection, allowing servers to resume streams from the last acknowledged event. ```javascript import { SSE } from "./sse.js"; const source = new SSE("/api/live", { autoReconnect: true, useLastEventId: true, headers: { "X-Client-ID": "dashboard-42" }, }); source.addEventListener("message", (e) => { // e.id → ID of this event (null if none) // e.lastEventId → last confirmed ID (persists across events) console.log(`event id=${e.id}, lastEventId=${e.lastEventId}`); // → "event id=evt-7, lastEventId=evt-7" }); // Inspect tracked ID at any time console.log("Current lastEventId:", source.lastEventId); // On reconnection, sse.js automatically adds: // Last-Event-ID: // to the XHR request headers — no manual action needed. ``` -------------------------------- ### Enable Last-Event-ID Support in SSE.js Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Configure SSE.js to automatically track and send the last received event ID on reconnection attempts. This is recommended for maintaining message continuity as per the SSE specification. ```javascript const source = new SSE(url, { useLastEventId: true, // Recommended: follows SSE specification }); ``` -------------------------------- ### Auto-Reconnect Configuration Source: https://context7.com/mpetazzoni/sse.js/llms.txt When `autoReconnect: true` is set, `sse.js` automatically schedules a reconnection attempt after every connection drop or error, waiting `reconnectDelay` ms between attempts. The retry counter resets to `0` on any successful connection. Calling `close()` permanently disables auto-reconnect. ```APIDOC ## Auto-Reconnect When `autoReconnect: true` is set, `sse.js` automatically schedules a reconnection attempt after every connection drop or error, waiting `reconnectDelay` ms between attempts. The retry counter resets to `0` on any successful connection. Calling `close()` permanently disables auto-reconnect. ```js import { SSE } from "./sse.js"; const source = new SSE("https://api.example.com/stream", { autoReconnect: true, reconnectDelay: 5000, // 5 s between attempts maxRetries: 10, // give up after 10 consecutive failures useLastEventId: true, // resume from last received event ID }); source.addEventListener("message", (e) => { console.log(`[${e.lastEventId}]`, JSON.parse(e.data)); }); source.addEventListener("open", (e) => { if (source.lastEventId) { console.log("Reconnected — resuming from event", source.lastEventId); } // retryCount resets to 0 here internally }); source.addEventListener("error", (e) => { if (source.maxRetries && source.retryCount >= source.maxRetries) { console.error("Max retries reached — giving up."); // autoReconnect is now false; connection is permanently closed } else if (source.autoReconnect) { console.warn( `Attempt ${source.retryCount + 1}/${source.maxRetries ?? "∞"} ` + `in ${source.reconnectDelay}ms…` ); } }); ``` ``` -------------------------------- ### Last-Event-ID Support Source: https://context7.com/mpetazzoni/sse.js/llms.txt `sse.js` automatically tracks the last received event ID in `source.lastEventId` and, on reconnection, sends it in the `Last-Event-ID` HTTP request header so the server can resume the stream without gaps. Controlled via `useLastEventId` (default `true`). ```APIDOC ## Last-Event-ID Support `sse.js` automatically tracks the last received event ID in `source.lastEventId` and, on reconnection, sends it in the `Last-Event-ID` HTTP request header so the server can resume the stream without gaps. Controlled via `useLastEventId` (default `true`). ```js import { SSE } from "./sse.js"; const source = new SSE("/api/live", { autoReconnect: true, useLastEventId: true, headers: { "X-Client-ID": "dashboard-42" }, }); source.addEventListener("message", (e) => { // e.id → ID of this event (null if none) // e.lastEventId → last confirmed ID (persists across events) console.log(`event id=${e.id}, lastEventId=${e.lastEventId}`); // → "event id=evt-7, lastEventId=evt-7" }); // Inspect tracked ID at any time console.log("Current lastEventId:", source.lastEventId); // On reconnection, sse.js automatically adds: // Last-Event-ID: // to the XHR request headers — no manual action needed. ``` ``` -------------------------------- ### Check Auto-Reconnect Status Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Dynamically check if auto-reconnect is enabled and the current retry count. ```javascript if (source.autoReconnect) { console.log("Auto-reconnect is enabled"); if (source.maxRetries) { console.log(`Attempt ${source.retryCount} of ${source.maxRetries}`); } } ``` -------------------------------- ### Access Last Event ID in SSE.js Source: https://github.com/mpetazzoni/sse.js/blob/main/README.md Retrieve the ID of the last successfully received event from the SSE instance. This property is useful for debugging or custom logic. ```javascript console.log("Last received event ID:", source.lastEventId); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.