shared-event-source
is a library that provides a shared EventSource connection across multiple browser tabs. It ensures that only one actual EventSource connection is open per URL, while other tabs receive events via a BroadcastChannel. This is particularly useful to get around the browser limit of maximum 6 non HTTP/2 SSE connections per domain.
Install the package via npm:
npm install shared-event-source
The SharedEventSource
class mimics the standard EventSource API but uses a BroadcastChannel and the Web Locks API to coordinate state between tabs.
import {SharedEventSource} from 'shared-event-source'
const eventSource = new SharedEventSource('https://example.com/events')
eventSource.onopen = () => {
console.log('Connection opened')
}
eventSource.onmessage = (event) => {
console.log('Message received:', event.data)
}
eventSource.onerror = () => {
console.error('An error occurred')
}
// Close the connection when done
// eventSource.close()
- Ensures only one EventSource connection per URL across all tabs.
- Automatically elects a new leader tab if the current leader closes.
- Broadcasts events to all tabs using the BroadcastChannel API.
new SharedEventSource(url: string, eventSourceInitDict?: EventSourceInit)
url
: The URL of the server-sent events stream.eventSourceInitDict
: Optional configuration, same as the standard EventSource.
url
: The URL of the EventSource.withCredentials
: Whether credentials are included in the request.readyState
: The current state of the connection (CONNECTING
,OPEN
, orCLOSED
).onerror
: Callback for error events.onmessage
: Callback for message events.onopen
: Callback for open events.
close()
: Closes the connection for this instance.
CONNECTING
: The connection is being established.OPEN
: The connection is open and receiving events.CLOSED
: The connection is closed.
This library requires a browser environment with support for:
BroadcastChannel
Web Locks API
MIT