Skip to content

useEventSource

See: EventSource or Server-Sent-Events connection to an HTTP server, which sends events in text/event-stream format.

Types

UseEventSourceProps

  • @template T Expected type of the parsed message data.

Configuration object accepted by useEventSource.

PropertyTypeRequiredDescription
urlstring \| URLURL of the SSE endpoint. Can be set here or passed to open() at connection time. If omitted, open() must always be called with a URL.
optsEventSourceInitOptions forwarded to the EventSource constructor. The most useful option is { withCredentials: true } for cross-origin SSE endpoints that require cookies or HTTP auth.
events{ name: string; handler?: (evt: MessageEvent) => void }[]Array of named events to listen to on the EventSource. Each entry registers a listener for the named event type alongside the default "message" listener.
immediateConnectionbooleanWhen true, the EventSource connection is opened immediately on mount. When false (default), call open() to connect.
onOpen(evt: Event) => voidCalled when the EventSource connection is established (open event).
onError(evt: Event) => voidCalled when an error occurs on the EventSource connection (error event). This includes connection errors and server-side errors.
onMessage<T>(evt: MessageEvent<T>) => voidCalled for every unnamed "message" event received from the server.

UseEventSourceResult

  • @template T Expected type of the parsed message data.

Result object returned by useEventSource.

PropertyTypeRequiredDescription
status"READY" \| "CONNECTING" \| "OPENED" \| "CLOSED"Current connection state of the EventSource: - "READY" — not yet connected (initial state). - "CONNECTING" — connection attempt in progress. - "OPENED" — connection established, receiving events. - "CLOSED" — connection closed (manually or by the server).
dataT \| nullThe most recently received "message" event data. null before the first message arrives.
open(url?: string) => voidOpens the EventSource connection to the provided (or configured) URL.
close() => voidCloses the EventSource connection. The status transitions to "CLOSED".

Released under the MIT License.