MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Server-Sent Events (SSE) for Real-Time Streaming0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
14.1WebSockets Architecture with Socket.io in React14.2Server-Sent Events (SSE) for Real-Time Streaming14.3Building a Collaborative Multi-User Canvas
HomeTutorialsReact.js for AdvancedServer-Sent Events (SSE) for Real-Time Streaming
Building a Collaborative Multi-User Canvas

Server-Sent Events (SSE) for Real-Time Streaming

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While WebSockets provide bidirectional communication, many real-time features are strictly unidirectional—data flows exclusively from server to client. Examples include generative AI LLM token streaming (ChatGPT / Gemini style responses), live stock tickers, server metric telemetry, and build progress notifications. Server-Sent Events (SSE) uses native HTTP to stream text events efficiently with less architectural overhead than WebSockets.


1. WebSockets vs Server-Sent Events (SSE)

FeatureWebSocketsServer-Sent Events (SSE)
DirectionalityFull-duplex (Bidirectional)Half-duplex (Server to Client only)
ProtocolCustom WS / WSS protocolStandard HTTP / HTTPS
HTTP/2 SupportLimited / Complex multiplexingNative HTTP/2 multiplexing (efficient)
ReconnectionMust be coded manuallyNative automatic reconnection built into browser
Firewall / Proxy TraversalsOften inspected or blockedBehaves like standard HTTP stream
Client APInew WebSocket()Native new EventSource() or fetch ReadableStream

2. Using Native EventSource

The browser's native EventSource interface handles automatic reconnection and event parsing:

1import React, { useEffect, useState } from "react";
2 
3interface TelemetryMetric {
4 cpuUsage: number;
5 memoryUsage: number;
6 activeRequests: number;
7 timestamp: string;
8}
9 
10export function SystemTelemetryDashboard() {
11 const [metric, setMetric] = useState<TelemetryMetric | null>(null);
12 const [status, setStatus] = useState<"connecting" | "connected" | "error">("connecting");
13 
14 useEffect(() => {
15 // 1. Establish SSE stream over standard HTTPS
16 const eventSource = new EventSource("https://api.enterprise.com/v1/metrics/stream");
17 
18 eventSource.onopen = () => {
19 setStatus("connected");
20 };
21 
22 // 2. Listen to unnamed default message events
23 eventSource.onmessage = (event) => {
24 const data: TelemetryMetric = JSON.parse(event.data);
25 setMetric(data);
26 };
27 
28 // 3. Listen to custom named events sent by the server
29 eventSource.addEventListener("alert", (event: MessageEvent) => {
30 const alertData = JSON.parse(event.data);
31 console.warn("System Alert Triggered:", alertData);
32 });
33 
34 eventSource.onerror = (err) => {
35 console.error("SSE connection failure:", err);
36 setStatus("error");
37 // Browser automatically retries connection in the background!
38 };
39 
40 // 4. Teardown stream on component unmount
41 return () => {
42 eventSource.close();
43 };
44 }, []);
45 
46 return (
47 <div className="p-6 bg-slate-900 border border-slate-800 rounded-xl text-white max-w-md">
48 <div className="flex justify-between items-center mb-4">
49 <h2 className="font-bold text-base">Server Telemetry (SSE)</h2>
50 <span
51 className={`text-xs px-2 py-0.5 rounded-full font-mono ${
52 status === "connected"
53 ? "bg-emerald-950 text-emerald-400 border border-emerald-800"
54 : "bg-rose-950 text-rose-400"
55 }`}
56 >
57 {status}
58 </span>
59 </div>
60 
61 {metric ? (
62 <div className="space-y-3 font-mono text-xs">
63 <div className="flex justify-between p-2 bg-slate-950 rounded">
64 <span className="text-slate-400">CPU Utilization:</span>
65 <span className="text-cyan-400 font-bold">{metric.cpuUsage}%</span>
66 </div>
67 <div className="flex justify-between p-2 bg-slate-950 rounded">
68 <span className="text-slate-400">Memory Usage:</span>
69 <span className="text-amber-400 font-bold">{metric.memoryUsage} MB</span>
70 </div>
71 <div className="flex justify-between p-2 bg-slate-950 rounded">
72 <span className="text-slate-400">Active Requests:</span>
73 <span className="text-emerald-400 font-bold">{metric.activeRequests} req/s</span>
74 </div>
75 </div>
76 ) : (
77 <p className="text-xs text-slate-500 italic">Streaming telemetry data...</p>
78 )}
79 </div>
80 );
81}

3. Streaming AI LLM Responses via fetch ReadableStream

While EventSource is simple, it only supports GET requests and cannot pass custom request body payloads or Authorization headers. For streaming AI completions (which require POST with JSON bodies), consume the response ReadableStream via fetch:

1import React, { useState } from "react";
2 
3export function AIResponseStreamer() {
4 const [output, setOutput] = useState("");
5 const [isGenerating, setIsGenerating] = useState(false);
6 
7 const triggerAIStream = async () => {
8 setOutput("");
9 setIsGenerating(true);
10 
11 try {
12 const response = await fetch("https://api.enterprise.com/v1/ai/generate", {
13 method: "POST",
14 headers: {
15 "Content-Type": "application/json",
16 Authorization: `Bearer ${sessionStorage.getItem("token")}`,
17 },
18 body: JSON.stringify({ prompt: "Explain React Fiber Architecture" }),
19 });
20 
21 if (!response.body) throw new Error("ReadableStream not supported");
22 
23 const reader = response.body.getReader();
24 const decoder = new TextDecoder("utf-8");
25 
26 while (true) {
27 const { value, done } = await reader.read();
28 if (done) break;
29 
30 const chunk = decoder.decode(value, { stream: true });
31 // Append streamed token chunks smoothly
32 setOutput((prev) => prev + chunk);
33 }
34 } catch (err) {
35 console.error("Stream failed:", err);
36 } finally {
37 setIsGenerating(false);
38 }
39 };
40 
41 return (
42 <div className="p-6 bg-slate-900 border border-slate-800 rounded-xl text-white max-w-xl">
43 <button
44 onClick={triggerAIStream}
45 disabled={isGenerating}
46 className="px-4 py-2 bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-800 rounded font-semibold text-sm mb-4"
47 >
48 {isGenerating ? "Streaming Tokens..." : "Generate AI Response"}
49 </button>
50 
51 <div className="p-4 bg-slate-950 border border-slate-800 rounded-lg min-h-[120px] text-sm text-slate-300 font-mono whitespace-pre-wrap">
52 {output || "Awaiting generation..."}
53 </div>
54 </div>
55 );
56}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary operational difference between WebSockets and Server-Sent Events (SSE)?
Question 2
What built-in capability does the browser's EventSource API provide without external libraries?
Question 3
Why is fetch ReadableStream used for AI LLM token streaming instead of EventSource?
Question 4
What HTTP Content-Type header must the server return to establish an SSE stream?
Question 5
Why must eventSource.close() be called in the useEffect cleanup function?
Next Lesson

Building a Collaborative Multi-User Canvas

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
WebSockets Architecture with Socket.io in ReactBuilding a Collaborative Multi-User Canvas

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext