use-shared-sse
Version:
React hook for sharing Server-Sent Events across tabs using BroadcastChannel and Web Locks.
51 lines (50 loc) • 1.67 kB
TypeScript
/**
* Configuration options for the `useSse` hook.
*/
interface UseSseOptions {
/**
* A string that represents the location of the remote resource serving the events/messages.
*/
url: string | URL;
/**
* Provides options to configure the new connection.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource#options | EventSource options on MDN}
*/
options?: EventSourceInit;
/**
* A list of server-sent events to subscribe to, each with a name and a corresponding callback.
*/
events: Array<{
/**
* Name of the event to listen for on the SSE connection.
*/
name: string;
/**
* Callback function that handles the received SSE message.
*/
cb: (event: MessageEvent) => void;
}>;
/**
* Optional custom name for the BroadcastChannel used for cross-tab communication.
* Defaults to "sse-channel".
*/
channelName?: string;
/**
* Optional custom name for the Web Lock used to prevent duplicate connections.
* Defaults to "sse-lock".
*/
lockName?: string;
}
/**
* This hook manages a single SSE connection across browser tabs using BroadcastChannel
* and Web Locks to prevent duplicate connections and synchronize events.
*
* @param options - Configuration for setting up the SSE connection. See `UseSseOptions`.
* @param options.url
* @param options.options
* @param options.events
* @param options.channelName
* @param options.lockName
*/
declare function useSse({ url, options, events, channelName, lockName }: UseSseOptions): void;
export { useSse };