https://github.com/starmordar/use-shared-sse
React hook that manages a single SSE connection across browser tabs using BroadcastChannel and Web Locks to prevent duplicate connections
https://github.com/starmordar/use-shared-sse
broadcast-channel cross-tab eventsource multitabs react react-hook server-sent-events sse web-locks
Last synced: 6 months ago
JSON representation
React hook that manages a single SSE connection across browser tabs using BroadcastChannel and Web Locks to prevent duplicate connections
- Host: GitHub
- URL: https://github.com/starmordar/use-shared-sse
- Owner: Starmordar
- License: mit
- Created: 2025-04-08T11:51:27.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2025-04-08T13:17:46.000Z (6 months ago)
- Last Synced: 2025-04-08T13:25:18.802Z (6 months ago)
- Topics: broadcast-channel, cross-tab, eventsource, multitabs, react, react-hook, server-sent-events, sse, web-locks
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/use-shared-sse
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# use-shared-sse


[](https://www.npmjs.com/package/use-shared-sse)
> 🔄 React hook to share a single Server-Sent Events (SSE) connection across multiple browser tabs using BroadcastChannel and Web Locks.
> ✅ Helps avoid browser HTTP/1.1 connection limits by ensuring only one active SSE connection across all tabs.## 📦 Installation
```bash
npm install use-shared-sse
```## 🚀 Quick Start
```tsx
import { useSse } from 'use-shared-sse';function SseExample() {
useSse({
url: 'http://localhost:3005/sse',
options: { withCredentials: true },
events: [
{ name: 'ping', cb: onPingEvent },
{ name: 'hero', cb: onHeroReceiveEvent },
],
});function onPingEvent(data: MessageEvent['data']) {
console.log('Ping:', data);
}function onHeroReceiveEvent(data: MessageEvent['data']) {
console.log('Hero:', data);
}return <>>;
}
```## 📚 API Reference
### `useSse(options: UseSseOptions)`
React hook that manages a shared SSE connection across browser tabs using `BroadcastChannel` and `Web Locks`.
---
### `UseSseOptions`
| Field | Type | Required | Description |
|---------------|------------------------------------------------|----------|-------------|
| `url` | `string \| URL` | ✅ Yes | The URL to open the SSE connection to. |
| `options` | `EventSourceInit` | No | SSE configuration object. Default is `{ withCredentials: true }`. See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource#options). |
| `events` | `{ name: string; cb: (event: MessageEvent) => void }[]` | ✅ Yes | A list of event listeners, each with an event name and handler. |
| `channelName` | `string` | No | Custom name for the `BroadcastChannel`. Default: `"sse-channel"`. |
| `lockName` | `string` | No | Custom name for the `Web Lock`. Default: `"sse-lock"`. |