Registry / http-networking / react-native-sse

react-native-sse

JSON →
library1.2.1jsnpmunverified

react-native-sse provides a robust, native-friendly `EventSource` implementation for React Native applications, enabling Server-Sent Events (SSE) on both iOS and Android platforms. The current stable version is 1.2.1, with a demonstrated active release cadence focused on features and fixes, as seen in recent minor updates. A key differentiator is its use of `XMLHttpRequest` internally, which eliminates the need for additional native module implementations, simplifying installation and integration. The library fully supports TypeScript, ensuring type safety for event listeners and configuration. It's commonly utilized for real-time data synchronization with systems like Mercure and is compatible with modern streaming APIs, including those used for AI interactions like ChatGPT. Its design prioritizes ease of use and broad compatibility within the React Native ecosystem.

npm install react-native-sse
INSTALL
IMPORT
SIG · REACT-NATIVE-SSE
R
react-native-sse
http-networkingjavascriptv1.2.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

EventSource
✓ import EventSource from 'react-native-sse';
✗ const EventSource = require('react-native-sse');
The library is designed for modern JavaScript environments; ESM `import` is the preferred and widely adopted method in React Native projects. While CJS `require` might technically work in some setups, it is generally discouraged for new code.
EventSourceListener
✓ import { EventSourceListener } from 'react-native-sse';
This is a TypeScript type definition used to strongly type event handler functions for better code safety and readability, especially when dealing with custom event types.

This example demonstrates how to establish an SSE connection, configure authentication with a Bearer token, listen for `open`, `message`, `error`, and `close` events, parse incoming JSON data, manage component state with real-time updates, and ensure proper connection cleanup in a React Native functional component.

import React, { useEffect, useState } from "react"; import { View, Text, StyleSheet } from "react-native"; import EventSource, { EventSourceListener } from "react-native-sse"; import "react-native-url-polyfill/auto"; // Use URL polyfill in React Native // Replace with your actual SSE server URL and token source const SSE_SERVER_URL = "https://demo.mercure.rocks/.well-known/mercure"; const MOCK_HUB_TOKEN = process.env.MOCK_HUB_TOKEN ?? "[your-actual-hub-token]"; // Use process.env for secure token handling interface Book { id: number; title: string; isbn: string; } const BookList: React.FC = () => { const [books, setBooks] = useState<Book[]>([]); const [connectionStatus, setConnectionStatus] = useState<string>("Connecting..."); const [error, setError] = useState<string | null>(null); useEffect(() => { const url = new URL(SSE_SERVER_URL); url.searchParams.append("topic", "/book/{bookId}"); // Example topic const es = new EventSource(url.toString(), { headers: { Authorization: { toString: function () { return "Bearer " + MOCK_HUB_TOKEN; }, }, }, timeoutBeforeConnection: 5000, // Optional: Timeout for connection attempt }); const listener: EventSourceListener = (event) => { if (event.type === "open") { console.log("SSE Connection Opened."); setConnectionStatus("Connected"); setError(null); } else if (event.type === "message") { try { const book = JSON.parse(event.data) as Book; setBooks((prevBooks) => { if (!prevBooks.some(b => b.id === book.id)) { return [...prevBooks, book]; } return prevBooks; }); console.log(`Received book ${book.title}, ISBN: ${book.isbn}`); } catch (parseError) { console.error("Failed to parse message data:", event.data, parseError); setError("Failed to parse event data."); } } else if (event.type === "error") { console.error("Connection error:", event.message); setConnectionStatus("Disconnected with error"); setError(event.message || "Unknown connection error"); } else if (event.type === "exception") { console.error("Internal Error:", event.message, event.error); setConnectionStatus("Disconnected with exception"); setError(event.message || "Unknown exception"); } }; es.addEventListener("open", listener); es.addEventListener("message", listener); es.addEventListener("error", listener); es.addEventListener("close", listener); // Listen to close events as well return () => { console.log("Cleaning up SSE connection."); es.removeAllEventListeners(); es.close(); }; }, []); // Empty dependency array ensures this runs once on mount/unmount return ( <View style={styles.container}> <Text style={styles.header}>Book Updates (SSE)</Text> <Text>Status: {connectionStatus}</Text> {error && <Text style={styles.errorText}>Error: {error}</Text>} {books.length === 0 ? ( <Text>Waiting for book updates...</Text> ) : ( books.map((book) => ( <View key={`book-${book.id}`} style={styles.bookItem}> <Text style={styles.bookTitle}>{book.title}</Text> <Text>ISBN: {book.isbn}</Text> </View> )) )} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 20, backgroundColor: '#f5f5f5', }, header: { fontSize: 24, fontWeight: 'bold', marginBottom: 10, }, bookItem: { backgroundColor: '#ffffff', padding: 15, borderRadius: 8, marginBottom: 10, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.2, shadowRadius: 1.41, elevation: 2, }, bookTitle: { fontSize: 18, fontWeight: '600', marginBottom: 5, }, errorText: { color: 'red', marginBottom: 10, } }); export default BookList;
Debug
Known issues
gotchaEvent listeners defined as closures within React `useEffect` hooks can capture stale props or state from their initial render. This leads to unexpected behavior where the listener operates on outdated values, especially when trying to update state based on current data.
fix
To ensure listeners always access the current state or props, either wrap the listener function in `useCallback` with appropriate dependencies, use a mutable ref (e.g., `useRef`) to hold the latest state, or retrieve the current state directly from a global state management solution like Redux within the listener callback.
affects: *
gotchaThe standard `URL` object's behavior might not be fully consistent across all React Native environments or older Hermes/JavaScript engines. The library's examples and documentation recommend explicitly importing `react-native-url-polyfill/auto` to ensure robust URL parsing and manipulation.
fix
Include `import 'react-native-url-polyfill/auto';` once at the entry point of your application (e.g., `index.js` or `App.tsx`) or wherever `URL` objects are constructed for SSE connection URLs.
affects: *
breakingPrior to version `1.2.1`, the `close` event might not have consistently dispatched in all scenarios, potentially leading to resource leaks or incorrect connection state management if relying solely on this event for cleanup. Issues related to text parsing with missing double newlines and alternative line endings were also addressed.
fix
Upgrade to `react-native-sse` version `1.2.1` or newer to benefit from fixes ensuring correct `close` event dispatching and improved compatibility with various SSE server implementations (e.g., `sse-starlette`). Always ensure `es.close()` is explicitly called during component unmount or when the connection is no longer needed.
affects: <1.2.1
Errors
Common errors & fixes
TypeError: Network request failed
The React Native client could not establish a network connection to the specified SSE server URL. This often indicates an incorrect URL, a server that is unreachable, network issues, or a server-side firewall/CORS configuration preventing the connection.
fix
Verify the SSE server URL is correct and accessible. Ensure the server is running and configured to serve SSE (e.g., `Content-Type: text/event-stream` header) and that there are no cross-origin resource sharing (CORS) policies preventing your React Native app's domain from connecting.
JSON Parse error: Unrecognized token '<' (or similar JSON parsing errors)
The `message` event's `data` property, expected to be a JSON string, instead contains HTML or some other non-JSON text. This usually happens when the SSE endpoint is returning an error page or unexpected content from the server instead of valid SSE data.
fix
Debug the SSE endpoint on the server side. Access the SSE URL directly in a web browser or using a tool like Postman to inspect the raw response. Ensure the server consistently sends `text/event-stream` with properly formatted SSE messages, ideally with JSON payloads if that is the expected data format.
Event listener callback does not reflect latest state/props
As described in warnings, a common React pattern where event listeners defined within `useEffect` hooks capture the component's state or props from the initial render, leading to stale closures. Subsequent renders with updated state do not automatically update the already-registered listener's scope.
fix
To make the listener dynamic, use `useCallback` to memoize the listener and list all relevant state/props in its dependency array. Alternatively, if using a global state management system, access the current state directly from the store instance within the listener.
Upgrade
Version history
1.2.1latest on npm
Audit
Dependencies
react-native-url-polyfill/autorequiredRecommended for consistent URL object behavior across React Native environments, particularly older ones, as standard URL object behavior can be inconsistent.
Agent activity
4 hits · last 30 days
node
4
Resources
react-native-sse — npm install react-native-sse · libregistry