Consuming SSE Streams in React with EventSource
Connect to an SSE endpoint with EventSource in useEffect and display streaming data in real time.
Consuming SSE Streams in React with EventSource is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Creating an EventSource Connection
new EventSource(url) creates an SSE connection to the specified URL. The browser immediately opens an HTTP GET request with the header Accept: text/event-stream. The server keeps this connection open and streams events. EventSource is a browser-native API — no library required for basic usage.
Connection Lifecycle States
EventSource has three ready states: 0 (CONNECTING) — connection is being established or re-established, 1 (OPEN) — connection is established and events are flowing, 2 (CLOSED) — connection is closed and will not reconnect. Check eventSource.readyState to determine the current state.
onmessage for Generic Events
The eventSource.onmessage handler fires for server events that do not have an explicit event type (the server sends data: ... without an event: field). The handler receives an event object where event.data is the string payload. The server typically JSON.stringify's the data so you JSON.parse it on receipt.
Named Custom Events
The server can send named events: event: userJoined
data: {"userId": "123"}
. In the browser, listen with eventSource.addEventListener('userJoined', handler). This allows multiplexing multiple event types over a single SSE connection — each event type has its own handler, making the code clean and organized.
Parsing event.data
SSE data arrives as strings. For structured data, the server sends JSON.stringify(payload) and the client parses it: const data = JSON.parse(event.data). Always wrap JSON.parse in try/catch to handle malformed JSON from the server gracefully, logging the error and skipping the malformed event.
useEffect for EventSource Lifecycle
Create and close EventSource inside a useEffect: create the connection when the component mounts, attach event handlers, and return a cleanup function that calls eventSource.close(). Without the cleanup, the connection leaks when the component unmounts, the user navigates away, or the effect re-runs with different dependencies.
Updating State on Message
Inside the eventSource.onmessage handler, update React state to reflect new data: setMessages(prev => [...prev, JSON.parse(event.data)]). Use the functional form of setState to avoid stale closure issues — the event handler captures the initial state value and the functional update ensures you always prepend to the latest state.
Automatic Reconnection
EventSource automatically reconnects when the connection is lost due to a network error or server restart. The browser waits a short delay (typically 3 seconds, configurable by the server via retry: 3000 in the stream) then reconnects. You do not need to implement reconnection logic — it is built into the EventSource API.
The Last-Event-ID Header
EventSource tracks the last received event ID (set by the server using id: 123 in the stream). When reconnecting, the browser automatically sends this ID in the Last-Event-ID HTTP header. A well-designed server uses this to replay missed events, ensuring no events are lost during a reconnection.
Passing Credentials and Headers
EventSource does not support custom headers directly. For authentication, use cookies (new EventSource(url, { withCredentials: true }) sends cookies) or include the auth token as a URL query parameter. If you need Authorization headers, use the Fetch API with ReadableStream instead of EventSource to process the SSE response manually.
Connection Error Handling
When EventSource encounters an error, the onerror handler fires. The readyState will be CONNECTING (if it will retry) or CLOSED (if not). In onerror, check readyState to distinguish between a temporary network error (will retry automatically) and a permanent failure (server returned non-200 status). For permanent errors, close the connection and notify the user.
EventSource Automatic Reconnection
What happens when an EventSource connection is dropped due to a network error?
Lesson Recap: EventSource in React
new EventSource(url) creates an SSE connection with readyStates: CONNECTING, OPEN, CLOSED. onmessage handles generic events; addEventListener handles named event types. JSON.parse(event.data) extracts structured payloads. Create and clean up EventSource in useEffect. Automatic reconnection is built in — EventSource retries after network errors with Last-Event-ID for missed-event replay. Authenticate via cookies (withCredentials) or URL query parameters.
Frequently asked questions
Is the “Consuming SSE Streams in React with EventSource” lesson free?
Yes — the full text of “Consuming SSE Streams in React with EventSource” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Consuming SSE Streams in React with EventSource”?
Connect to an SSE endpoint with EventSource in useEffect and display streaming data in real time. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Consuming SSE Streams in React with EventSource” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SSE vs WebSockets vs Polling Comparison
- Consuming SSE Streams in React with EventSource
- Long Polling Pattern and Reconnection Logic
- Building a Real-Time Notification Feed