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)0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
11.1WebSockets for Real-Time Bidirectional Communication11.2Server-Sent Events (SSE)11.3Fetch Interceptors & Request Middleware11.4GraphQL Queries, Mutations & Subscriptions
HomeTutorialsJavaScript for AdvancedServer-Sent Events (SSE)
Fetch Interceptors & Request Middleware

Server-Sent Events (SSE)

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

While WebSockets excel at bidirectional communication, many real-world applications only need unidirectional updates from the server to the client—such as real-time stock quotes, AI streaming text responses (like ChatGPT / LLMs), live sports scores, and social notifications. Server-Sent Events (SSE) provide a lightweight, HTTP-based streaming protocol with built-in reconnection.


1. SSE vs. WebSockets

FeatureServer-Sent Events (SSE)WebSockets
DirectionUnidirectional (Server -> Client only)Bidirectional (Full Duplex)
ProtocolStandard HTTP / HTTPSCustom WS / WSS protocol
HTTP/2 MultiplexingFully supported out of the boxRequires separate TCP connection
Automatic ReconnectionBuilt-in natively by the browserMust be coded manually
Firewall / Proxy FriendlyPasses standard HTTP proxies easilySometimes blocked by corporate proxies
Data FormatUTF-8 text streams (often JSON)Text and Binary (Blob, ArrayBuffer)

2. The EventSource Client API

Consuming an SSE stream in JavaScript requires just a few lines using the native EventSource API:

1// Connect to SSE stream endpoint over standard HTTPS
2const eventSource = new EventSource('/api/v1/live-feed');
3 
4// 1. Connection Opened
5eventSource.onopen = () => {
6 console.log('[SSE] Streaming connection established.');
7};
8 
9// 2. Default Message Handler
10eventSource.onmessage = (event) => {
11 const data = JSON.parse(event.data);
12 console.log('[SSE] Default update received:', data);
13};
14 
15// 3. Named Custom Events (Dispatched by server 'event: update_stock')
16eventSource.addEventListener('stock_tick', (event) => {
17 const stock = JSON.parse(event.data);
18 console.log(`Stock ${stock.ticker} updated: $${stock.price}`);
19});
20 
21// 4. Error Handling (Browser auto-reconnects automatically!)
22eventSource.onerror = (err) => {
23 if (eventSource.readyState === EventSource.CLOSED) {
24 console.log('[SSE] Connection closed by server.');
25 } else {
26 console.warn('[SSE] Connection interrupted. Browser will auto-reconnect.');
27 }
28};
29 
30// Close connection manually:
31// eventSource.close();

3. Server-Side Protocol Format

SSE operates over standard HTTP with headers:

  • Content-Type: text/event-stream
  • Cache-Control: no-cache
  • Connection: keep-alive

The Raw Wire Format:

1event: stock_tick
2id: 10492
3data: {"ticker": "NVDA", "price": 138.50}
4 
5event: stock_tick
6id: 10493
7data: {"ticker": "AAPL", "price": 225.10}
8 
  • data: The payload string. Multiple lines are joined with newlines.
  • id: The message sequence ID. If connection drops, the browser sends Last-Event-ID: 10493 upon reconnecting so the server can resume missed messages!
  • event: The event type for addEventListener().
  • Double Newline \n\n: Delimits the end of each message frame.

4. Consuming POST Streams with Fetch (AI LLM Streaming)

Standard EventSource only supports GET requests without custom authorization headers. For AI chat completions (POST requests sending message history), stream using the Fetch API with ReadableStream:

1async function streamAiResponse(prompt) {
2 const response = await fetch('/api/chat/stream', {
3 method: 'POST',
4 headers: {
5 'Content-Type': 'application/json',
6 'Authorization': 'Bearer YOUR_TOKEN'
7 },
8 body: JSON.stringify({ prompt })
9 });
10 
11 const reader = response.body.getReader();
12 const decoder = new TextDecoder('utf-8');
13 
14 while (true) {
15 const { value, done } = await reader.read();
16 if (done) break;
17 
18 const chunk = decoder.decode(value);
19 // Append incoming token text to UI in real-time!
20 processStreamingChunk(chunk);
21 }
22}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary communication direction supported by Server-Sent Events (SSE)?
Question 2
What browser API is used natively to consume Server-Sent Events?
Question 3
What happens if an SSE connection is dropped due to temporary network failure?
Question 4
What HTTP Content-Type header must the server send for Server-Sent Events?
Question 5
When is Server-Sent Events preferred over WebSockets?
Next Lesson

Fetch Interceptors & Request Middleware

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

Related Lessons

Previous LessonNext Lesson
WebSockets for Real-Time Bidirectional CommunicationFetch Interceptors & Request Middleware

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript 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