WarningThe 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.
NoteServer-Sent Events are unidirectional. If you require bidirectional communication (sending data to the server), consider using useWebsocket.
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.
| Name | Type | Description |
|---|---|---|
| url | string | The URL of the server-side script that sends the events. |
| options.enabled | boolean | Whether the connection should be established immediately. Default: true. |
| options.onOpen | (event: Event) => void | Callback triggered when the connection is successfully opened. |
| options.onMessage | (event: MessageEvent) => void | Callback triggered whenever a new message event is received from the server. |
| options.onError | (event: Event) => void | Callback triggered when a connection error occurs. |
| options.withCredentials | boolean | Whether the browser should send cookies or HTTP authentication with the request. Default: false. |
| Name | Type | Description |
|---|---|---|
| readyState | number | null | The current state of the connection: 0 (Connecting), 1 (Open), or 2 (Closed). |
| close | () => void | Manually closes the connection and prevents further updates. |
This demo uses a public SSE endpoint that only sends keep-alive comments. Connection opens successfully, but no message events are emitted.