Challenge 3: Set Up an SSE Connection — Possible Solution ==================================================================== const notificationStream = new EventSource("/api/notifications/stream"); notificationStream.onmessage = (event) => { const notification = JSON.parse(event.data); console.log("Received notification:", notification); }; notificationStream.onerror = (error) => { console.log("SSE connection lost — attempting to reconnect...", error); // No manual reconnect() call is needed here — see the "why" below — // this handler exists purely to observe/log the event, not to trigger // recovery. }; notificationStream.onopen = () => { console.log("SSE connection established."); }; WHY THIS WORKS -------------- - new EventSource("/api/notifications/stream") immediately opens a persistent HTTP connection to that URL and starts listening for server-pushed events — no separate "connect" call is needed, unlike WebSockets' more manual connection lifecycle covered in later chapters. - onmessage fires once per event the server sends; event.data is always a string, so JSON.parse() is needed to turn it back into a structured object if the server is sending JSON-formatted notification payloads (a very common convention, though SSE itself is transport-agnostic about the payload format). - onerror fires when the connection is lost or fails — critically, the browser's EventSource implementation ALREADY handles reconnection automatically behind the scenes by default, retrying the connection on its own after an error. This handler is for observability (logging, updating a "reconnecting..." UI indicator) rather than for manually re-establishing the connection, which is exactly the "genuinely simpler than WebSockets" advantage the chapter highlighted — no hand-rolled reconnect() logic is required the way it typically is for raw WebSockets (covered in Chapter 5). - onopen is optional but useful for confirming the initial connection succeeded, and for distinguishing "just connected" from "reconnected after a drop" in more detailed logging if needed.