react-eventsource-hook
Version:
⚠️ DEPRECATED: Use 'react-eventsource' instead. React hook for Server-Sent Events with custom headers support, built on @microsoft/fetch-event-source
178 lines (136 loc) • 5.64 kB
Markdown
# react-eventsource-hook
> ⚠️ **DEPRECATED** - This package is no longer maintained. Please use [`react-eventsource`](https://www.npmjs.com/package/react-eventsource) instead.
[](https://www.npmjs.com/package/react-eventsource-hook)
[](https://www.npmjs.com/package/react-eventsource-hook)
[](./LICENSE)
## Migration Guide
This package is deprecated and no longer maintained. Please migrate to [`react-eventsource`](https://www.npmjs.com/package/react-eventsource) which provides similar functionality with better maintenance and features.
### Quick Migration
**Before (this package):**
```bash
npm install react-eventsource-hook
```
**After (recommended):**
```bash
npm install react-eventsource
```
### API Changes
The API is very similar, but there are some differences. Please refer to the [`react-eventsource` documentation](https://www.npmjs.com/package/react-eventsource) for the exact API.
---
## Legacy Documentation
*The following documentation is kept for reference only. This package is no longer maintained.*
A simple React hook for Server-Sent Events with the key feature that native EventSource lacks: **custom headers support**.
Perfect for authenticated Server-Sent Events, API keys, and any scenario where you need to send headers with your SSE connection.
## Installation
```bash
npm install react-eventsource-hook
```
## Quick Start
```tsx
import React from 'react'
import { useEventSource } from 'react-eventsource-hook'
function ServerUpdates() {
const { readyState, close, reconnect } = useEventSource({
url: '/api/events',
headers: {
'Authorization': 'Bearer your-token',
'X-API-Key': 'your-api-key'
},
onMessage: (message) => {
console.log('Received:', message.data)
},
onError: (error) => {
console.error('SSE Error:', error)
}
})
const status = ['CONNECTING', 'OPEN', 'CLOSED'][readyState]
return (
<div>
<p>Connection: {status}</p>
<button onClick={close}>Close</button>
<button onClick={reconnect}>Reconnect</button>
</div>
)
}
```
## API Reference
### `useEventSource(options)`
#### Options
| Property | Type | Required | Description |
|-------------|-------------------------------------------|----------|---------------------------------------|
| `url` | `string` | Yes | Server-Sent Events endpoint URL |
| `headers` | `Record<string, string>` | No | Custom headers (auth, API keys, etc.) |
| `method` | `string` | No | HTTP method (defaults to 'GET') |
| `body` | `string \| FormData` | No | Request body (rarely needed for SSE) |
| `onMessage` | `(message: EventSourceMessage) => void` | No | Message event handler |
| `onOpen` | `(response: Response) => void` | No | Connection open handler |
| `onError` | `(error: unknown) => void` | No | Error handler |
| `fetch` | `typeof window.fetch` | No | Custom fetch implementation |
#### Return Values
| Property | Type | Description |
|--------------|--------------|--------------------------------------------------------|
| `readyState` | `number` | Connection state: 0=CONNECTING, 1=OPEN, 2=CLOSED |
| `close` | `() => void` | Manually close the connection |
| `reconnect` | `() => void` | Close current connection and immediately reconnect |
## Examples
### Authenticated Events
```tsx
useEventSource({
url: '/api/user-notifications',
headers: {
'Authorization': `Bearer ${userToken}`
},
onMessage: (msg) => {
const notification = JSON.parse(msg.data)
showNotification(notification)
}
})
```
### POST with Body (Advanced)
```tsx
useEventSource({
url: '/api/stream',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-User-ID': userId
},
body: JSON.stringify({
channels: ['updates', 'alerts']
}),
onMessage: handleStreamMessage
})
```
### Connection Management
```tsx
function ChatStream() {
const { readyState, close, reconnect } = useEventSource({
url: '/api/chat-stream',
headers: { 'Authorization': `Bearer ${token}` },
onMessage: (msg) => addMessage(JSON.parse(msg.data)),
onError: (err) => console.error('Chat stream error:', err)
})
const isConnected = readyState === 1
return (
<div>
<div className={`status ${isConnected ? 'connected' : 'disconnected'}`}>
{isConnected ? '🟢 Connected' : '🔴 Disconnected'}
</div>
<button onClick={reconnect} disabled={readyState === 0}>
Reconnect
</button>
<button onClick={close}>
Disconnect
</button>
</div>
)
}
```
## Why This Hook?
- **Native EventSource limitation**: Cannot send custom headers
- **This hook solves that**: Built on `@microsoft/fetch-event-source` which supports headers
- **React-friendly**: Manages connection lifecycle with useEffect
- **Simple API**: Familiar EventSource-like interface
- **TypeScript**: Full type safety out of the box
## License
MIT License. See [LICENSE](./LICENSE) for details.