S42Core Server Side Events
SSE
Overview
The SSE
class provides a simplified interface for handling Server-Sent Events (SSE) in a Node.js application. SSE allows servers to push updates to the client over an HTTP connection, ideal for real-time applications where data needs to be pushed from the server to the client without frequent polling.
Purpose
The primary goal of the SSE
class is to establish and manage an SSE connection, send events to the client, and handle the connection lifecycle, including closing the connection gracefully.
Key Features
- Automatic Connection Setup: Sets up the response headers needed for SSE and sends an initial welcome event.
- Event Sending: Allows for sending custom events to the client.
- Connection Management: Handles the setup and teardown of SSE connections.
- UUID Generation: Generates a unique identifier for each SSE connection.
Methods
constructor(req: IncomingMessage, res: ServerResponse)
Initializes a new SSE connection by setting the appropriate headers and sending a welcome event to the client.
- req: The HTTP request object.
- res: The HTTP response object.
Usage
getUUID(): string
Returns the unique UUID associated with this SSE connection.
- returns: A string representing the UUID.
Usage
send(data: TypeSSEventToSend)
Sends a custom event to the client over the established SSE connection.
- data: An object containing:
- eventName: The name of the event to be sent.
- eventPayload: An object containing the event data as key-value pairs.
Usage
close()
Closes the SSE connection gracefully.
Usage
Use Cases
Example: Basic SSE Setup
This example demonstrates how to set up a basic SSE connection and send events from a Node.js server.
This example shows how to use the SSE
class to establish a Server-Sent Events connection, send events, and close the connection after a certain period.
Browser implementation
Response after connected
The server side events controller will return a new event “welcome” with the uuid
prop into “eventPayload”.