useServerSentEvent

A React hook that provides unopinionated access to the EventSource Web API for receiving real-time server-side updates.

Warning

The native EventSource API does not support custom HTTP headers (like Authorization). If your endpoint requires them, you may need a different approach or a polyfill.

Note

Server-Sent Events are unidirectional. If you require bidirectional communication (sending data to the server), consider using useWebsocket.

Installation

bash

Description

The useServerSentEvent hook manages the lifecycle of a Server-Sent Events (SSE) connection. Unlike WebSockets, SSE is a unidirectional protocol where the server pushes data to the client over HTTP. This hook handles the initialization, provides reactive connection status through readyState, and ensures the connection is properly closed when the component unmounts or is manually terminated.

Parameters

NameTypeDescription
urlstringThe URL of the server-side script that sends the events.
options.enabledbooleanWhether the connection should be established immediately. Default: true.
options.onOpen(event: Event) => voidCallback triggered when the connection is successfully opened.
options.onMessage(event: MessageEvent) => voidCallback triggered whenever a new message event is received from the server.
options.onError(event: Event) => voidCallback triggered when a connection error occurs.
options.withCredentialsbooleanWhether the browser should send cookies or HTTP authentication with the request. Default: false.

Return values

NameTypeDescription
readyStatenumber | nullThe current state of the connection: 0 (Connecting), 1 (Open), or 2 (Closed).
close() => voidManually closes the connection and prevents further updates.

Demo

This demo uses a public SSE endpoint that only sends keep-alive comments. Connection opens successfully, but no message events are emitted.

Server-Sent Event

Status:

Source code

tsx