use-sse-events
v1.0.2
React hook · Server-Sent Events

SSE.
Finally
done
right.

~1.5kB
gzipped size
ZERO
dependencies
TS 6
fully typed
SSR
Next.js safe

01

Zero dependencies

Pure React and browser APIs. No bloat, no surprise transitive deps.

02

Auto-reconnection

Resilient by default. Configurable intervals, no manual wiring.

03

Custom events

Named server events with a clean, declarative handler API.

04

SSR safe

Works with Next.js App Router and server components from day one.

Quick start

Up in 30 seconds.

Install and drop into any client component. No provider, no config, no ceremony.

'use client'

import { useSSE } from 'use-sse-events'

function App() {
  const { isConnected } = useSSE({
    url: '/api/sse',
    onMessage: (e) =>
      console.log('New message:', e.data),
  })

  return (
    <p>
      {isConnected ? 'Connected' : 'Disconnected'}
    </p>
  )
}

Reference

API Options

urlrequired

string

The SSE endpoint URL to connect to.

enabled

boolean

Toggle the connection on/off without unmounting the component.

withCredentials

boolean

Whether to send cookies along with the SSE request.

reconnectInterval

number

Milliseconds to wait before each reconnect attempt. Default: 3000.

onOpen

() => void

Fires when the connection is successfully established.

onConnected

(e: MessageEvent) => void

Fires on the server-side connected event.

onMessage

(e: MessageEvent) => void

Fires on every default message event from the server.

onReconnecting

({ delay: number }) => void

Fires before each reconnection attempt, with the delay value.

onNotification

(e: MessageEvent) => void

Fires on notification events from the server.

onHeartbeat

(e: MessageEvent) => void

Fires on heartbeat events to detect connection health.

onError

(error: Event) => void

Fires when a connection error occurs.

customEvents

Record<string, (e: MessageEvent) => void>

Map of named server event types to their respective handlers.