🖧 What is Server-Sent Events (SSE)?

Imagine you are watching live cricket scores on a website. The scores update automatically, without you refreshing the page.

💡 This happens because the server keeps sending new scores to your browser and the browser updates the page. This is exactly what SSE does.

SSE is a way for the server to push updates to the browser without the browser asking for them repeatedly.


➡️ When Should You Use SSE?

SSE is great for cases where real-time updates are needed, such as:

Use Case Example
🔥 Live Scores Cricket, Football, or Stock Updates
🗞️ News Feeds Breaking News Websites
💬 Chat Apps Messages Coming in Real-Time
📊 Live Dashboards Monitoring System Data

🚀 Key Feature: The page updates without refreshing!


➡️ How SSE Works?

1️⃣ The server keeps sending updates.
2️⃣ The browser (webpage) listens and updates automatically.
3️⃣ Uses a single connection, reducing server load compared to frequent AJAX requests.

💡 Think of SSE as a radio station 🎙️ broadcasting news, and your browser is the radio 📻 listening to updates!


➡️ Let’s Create a Simple SSE Example

😎 What Will We Build?

A webpage that shows live time updates from the server every 2 seconds.

☑ No page refresh needed!

☑ Lightweight & easy to use!


👩🏽‍💻 Step 1: Create the Backend (Server)

We will use Node.js to create a simple server that sends time updates.

📝 Create a file server.js and add this code:

const http = require("http"); // Import built-in HTTP module

http.createServer((req, res) => {
    if (req.url === "/events") {  // Check if the request is for SSE
        res.writeHead(200, {
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive"
        });

        setInterval(() => {
            const time = new Date().toLocaleTimeString();
            res.write(`data: ${time}\n\n`); // Send updated time to the client
        }, 2000);
    }
}).listen(3000, () => console.log("Server running on port 3000"));

📌 Explanation:

  • http.createServer() creates a simple server.
  • If the user visits /events, the server sends real-time updates.
  • setInterval() sends the current time every 2 seconds.
  • res.write() sends the time update to the browser.
  • The server runs on port 3000.

🛠️ Run the Server:

  1. Open the terminal (Command Prompt).
  2. Navigate to the folder where server.js is saved.
  3. Run: node server.js
  4. You should see "Server running on port 3000" 🎉

👩🏽‍💻 Step 2: Create the Frontend (HTML Page)

Now, we need a webpage to receive and display the live time updates.

📝 Create a file index.html and add this code:

</span>
 lang="en">

     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0">
    Live Time Updates


    Live Time from Server
     id="time">Waiting for updates...  

    
        // Connect to the server using SSE
        const eventSource = new EventSource("http://localhost:3000/events");

        // When a new message (update) arrives, update the webpage
        eventSource.onmessage = (event) => {
            document.getElementById("time").innerText = event.data;
        };
    





    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  📌 Explanation:


new EventSource("http://localhost:3000/events") connects to the server and listens for updates.
Whenever the server sends a new time, onmessage updates the page.

No refresh needed! 

  
  
  👩🏽‍💻 Final Step: Run the Project
❶ Start the server: node server.js
❷ Open index.html in a browser
❸ See the live time updating every 2 seconds!  
  
  
  ➡️ Why Use SSE Instead of Other Methods?



Feature
Server-Sent Events (SSE)
WebSockets
AJAX Polling




📡 Connection Type
One-way (Server ➡️ Browser)
Two-way
Multiple Requests


🔄 Auto Updates
✅ Yes
✅ Yes
❌ No


⚡ Performance
✅ Efficient
⚡ Best
❌ High Load


🔗 Complexity
✅ Simple
❌ Complex
⚠️ Medium


🔹 Use SSE when you need one-way live updates (like news, stock prices).
🔹 Use WebSockets when you need two-way communication (like chat apps).
🔹 Avoid AJAX polling for frequent updates as it wastes resources!
  
  
  ➡️ Important Points

SSE lets a server send automatic updates to a browser.
It’s easy to use with just JavaScript (No extra libraries needed!).
Great for live updates (news, dashboards, sports scores).
Uses less bandwidth compared to AJAX polling.

Works in most browsers, except older versions of Internet Explorer.


  
  
  ➡️ Next Steps
↪ Try modifying the server to send random jokes instead of time!
↪ Experiment with multiple clients (open index.html in different tabs).
↪ Learn about WebSockets for two-way communication.
  
  
  🙌 Hope you found this helpful! 🤗