DEV Community

Cover image for Say Goodbye to WebSockets? Why SSE Might Be Your New Best Friend
zakaria chahboun
zakaria chahboun

Posted on

Say Goodbye to WebSockets? Why SSE Might Be Your New Best Friend

Introduction

Hey fellow devs! πŸ‘‹ Today, let's dive into Server-Sent Events (SSE) and explore why they might be your next favorite tool for real-time communication. If you've been relying on traditional request-response methods or wrestling with WebSocket complexity, SSE might be the simpler solution you've been looking for!

Table of Contents

What are Server-Sent Events?

SSE is a standard that enables servers to push real-time updates to clients over a single HTTP connection. Think of it as a one-way communication channel where your server can send updates whenever it wants, without the client having to ask for them repeatedly.

Key Benefits

1. Low Latency for Real-Time Updates

Imagine you're building a chat app. Instead of your users constantly asking "any new messages?" (polling), the server can instantly push new messages to them.

2. Efficient Resource Usage

No more polling! The server only sends data when there's actually something new to share.

3. Simpler than WebSockets

While WebSockets are powerful, SSE uses standard HTTP and is much simpler to implement.

4. Built-in Reconnection

Lost connection? No worries! SSE automatically handles reconnection for you.

SSE Message Format

Before we jump into the code, let's understand the SSE message format. The server sends messages in this format:

event: myevent    // Optional: name of the event
data: message     // The actual message content
id: 123          // Optional: event ID for resuming connection
retry: 10000     // Optional: reconnection time in milliseconds

Enter fullscreen mode Exit fullscreen mode

Each field must end with a newline (\n), and the message must end with two newlines (\n\n).

Simple Code Examples

Backend (Go)

package main

import (
    "fmt"
    "net/http"
    "time"
)

func sseHandler(w http.ResponseWriter, r *http.Request) {
    // Set headers for SSE
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    // Check if the ResponseWriter supports flushing
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
        return
    }

    // Sending events every second
    for i := 0; i < 10; i++ {
        // Write SSE event format
        fmt.Fprintf(w, "event:welcome\ndata: Message %d\n\n", i)

        // Flush the response to send the event immediately
        flusher.Flush()

        // Simulate a delay
        time.Sleep(time.Second)
    }
}

func main() {
    http.HandleFunc("/events", sseHandler)
    fmt.Println("Server listening on :8080")
    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • w.Header().Set("Content-Type", "text/event-stream"): Ensures the client treats this as an SSE connection.
  • w.Header().Set("Cache-Control", "no-cache"): Prevents caching of the SSE stream.
  • w.Header().Set("Connection", "keep-alive"): Keeps the connection open for continuous

Frontend (JavaScript)

// Basic SSE connection
const eventSource = new EventSource('http://localhost:8080/events');

// Handle regular messages
eventSource.onmessage = (event) => {
    console.log('Received message:', event.data);
    document.getElementById('messages').innerHTML += `<p>${event.data}</p>`;
};

// Handle named events
eventSource.addEventListener('welcome', (event) => {
    console.log(event.data);
});

// Handle connection open
eventSource.onopen = () => {
    console.log('Connection opened!');
};

// Handle errors
eventSource.onerror = (error) => {
    console.log('Error occurred:', error);
};

// To close connection when needed
function closeConnection() {
    eventSource.close();
}
Enter fullscreen mode Exit fullscreen mode

SSE vs WebSockets: When to Use What? 🀹

While both SSE and WebSockets are used for real-time communication, here’s a quick comparison:

Feature SSE WebSockets
Communication One-way (server to client) Two-way (bi-directional)
Setup Complexity Simpler (works over HTTP) More complex (requires WebSocket protocol)
Client Support Well-supported by modern browsers Supported in most modern browsers
Use Case Ideal for notifications, live feeds, data updates Ideal for chat, multiplayer games, full-duplex communication
Reconnection Automatic reconnection built-in Must handle reconnection manually

Best Use Cases for SSE 🎯

  1. Live notifications
  2. Real-time dashboards
  3. Stock market updates
  4. Social media feeds
  5. Live sports scores
  6. System monitoring

Pro Tips πŸ’‘

  1. Message Types: You can send different types of events:
   // Regular message
   data: Your message here\n\n

   // Named event
   event: userconnected\n
   data: John joined\n\n

   // Multiple data lines
   data: line 1\n
   data: line 2\n\n
Enter fullscreen mode Exit fullscreen mode
  1. Reconnection Control: Set custom retry time:
   retry: 5000\n\n
Enter fullscreen mode Exit fullscreen mode
  1. Event IDs: Track message sequence:
   id: 12345\n
   data: Your message here\n\n
Enter fullscreen mode Exit fullscreen mode
  1. Full Example: All SSE Properties:
   event: notification\n
   data: Payment is successful\n
   retry: 5000\n
   id: transaction-id-12345\n\n

   event: notification\n
   data: Shipping update: Your package has been dispatched\n
   retry: 5000\n
   id: shipping-id-98765\n\n
Enter fullscreen mode Exit fullscreen mode

Conclusion πŸŽ‰

SSE is a powerful yet simple tool for real-time updates. It's perfect when you need server-to-client updates without the complexity of WebSockets. The built-in features like automatic reconnection and the simple HTTP-based protocol make it a great choice for many real-time applications.

Have you used SSE in your projects? What has been your experience? Let me know in the comments below! πŸ‘‡


Happy coding! πŸ‰

Top comments (42)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

A warning: you're probably going to still need some kind of polling fallback. These days I check for receipt acknowledgement and then use the SSE stream for polling, which works, but the server has to close the connection if it doesn't get an "ack".

Collapse
 
zakariachahboun profile image
zakaria chahboun

Cool, thanks for sharing! I will read it. πŸ™

Collapse
 
kundan_kumar_7516aa7be04a profile image
KUNDAN KUMAR

True. I am still struggling to configure nginx properly for SSE

Collapse
 
miketalbot profile image
Mike Talbot ⭐
res.set({
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache, no-store, must-revalidate",
        Pragma: "no-cache",
        Expires: "0",
        "Transfer-Encoding": "chunked",
        Connection: "keep-alive",
        "Access-Control-Allow-Origin": process.env.ORIGIN || request.get("origin") || "*",
        "X-Accel-Buffering": "no",
    })
Enter fullscreen mode Exit fullscreen mode

These are the headers I send

Collapse
 
rcls profile image
OssiDev • Edited

It's amazing that I've been at this for 15+ years and I'm still discovering new things like server-sent events. It was proposed 20 years ago already and somehow I've missed it completely. Simply never bumped into it.

Thanks for this post!

Collapse
 
zakariachahboun profile image
zakaria chahboun

Glad this post brought it to your attention! Do you think you'll use SSE in any of your projects?

Collapse
 
elanza48 profile image
Elanza-48

The title of the post is very misleading. You might get excited when you learn new things that doesn't mean "Saying goodbye to something", just for views don't do such nonsense.

Collapse
 
zakariachahboun profile image
zakaria chahboun

Not everything has to be taken so seriouslyβ€”sometimes a catchy title is just that. Take it easy!

Collapse
 
budgiewatts profile image
John Watts

Click bait is always click bait.

Collapse
 
octavio_santi_a4949b71ce5 profile image
Octavio Santi • Edited

I dont think this will replace the websockets, its just another technology for different use cases. SSE is for one way comunication and is more related to send notifications between the client and the server (for example in my job we have a react app who run inside of a 3rd party old electron app who has our app inside of an iframe and we needed to use SSE for sending an event to revoke all cookies in the electron application). If I need a chat or something "in real time" id still prefer to use web socket, things like push notifications SSE is the best choice

Collapse
 
zakariachahboun profile image
zakaria chahboun

Of course, it's not a replacement because they serve different purposes. But if you want to deal with real-time data, you should consider SSE first. If you need a more complex, duplex channel, then WebSockets are the way to go!

Collapse
 
rslhelper profile image
rslhelper

witching from WebSockets to SSE sounds like a big shift! SSE’s simplicity and lower overhead make it a strong alternative, especially for real-time updates. Curious to see how it holds up in high-demand applications!

Collapse
 
zakariachahboun profile image
zakaria chahboun

Try it and tell us πŸ˜‰

Collapse
 
5p4r70n profile image
jothish

It's just a brodcaster?
How the authorisation works here?
If there is 100 users , everyone will get everyones data??
I'm sorry I'm just a noob trying new things

Collapse
 
troy_high_e57325ac3b2b98c profile image
Troy High

@5p4r70n , you would have to use your existing auth model. For example, we use sse to send notifications to users of our system when they are in the admin console. The app uses tokens so the server only receives authenticated messages.

Also since we have info on the user via the token we store some identifier info on the cached connection pool so when a SSE is generated we can send only to clients that match the recipient id.

Collapse
 
peerreynders profile image
peerreynders

SSE is simplest described as a regular HTTP request with a streaming response; the streaming payload is events.

  • The server closing the response is unexpected, so the client sends another request to start again.
  • The client will close the connection when it is done with the request.

WS requests on the other hand convert (β€œupgrade”) the HTTP request to something outside of the HTTP spec to get access to the sockets that the original HTTP request was using.

In both cases the server has to manage a distinct connection to each user; however SSE connections tend to be less demanding on server resources and SSE may work where WS won't; like when firewalls block non-HTTP traffic. But both require an always-on server,so neither of them is suitable for a serverless environment.

Collapse
 
5p4r70n profile image
jothish

Ok, go it

The server and client will keep this connection alive for future server-to-client event notifications.

Thanks! 😊

Collapse
 
zakariachahboun profile image
zakaria chahboun

Great questions! SSE isn't just a broadcasterβ€”it's a way for the server to push updates to clients in real-time over a single HTTP connection.

As for authorization, it usually works by validating the user's identity before establishing the SSE connection, just like any other secure connection.

// Sends a GET request to /events
const eventSource = new EventSource('/events', {
    headers: {
        'Authorization': 'Bearer your_token_here'
    }
});

// Or Cookies
const eventSource = new EventSource('/events', {
    withCredentials: true // Ensures cookies and credentials are sent with the request
});
Enter fullscreen mode Exit fullscreen mode

The server responds with an HTTP response that has a Content-Type: text/event-stream header and keeps the connection open to send multiple events over time.

Regarding your last question: If you have 100 users, each client will only receive the data that the server sends to it. Typically, you would send specific updates based on the user’s permissions or the data they’re subscribed to, so not everyone gets everyone else's data.

Collapse
 
naveen_kumar_1949a763d392 profile image
Naveen Kumar

Few days back, we got a requirement where our DAO layer is collecting data from some files in the backend, as now this data can be large and we cannot load the complete data in memory hence we thought of going with SSE where server can send the data in chunks to Client in stream without loading the complete data.
In this case also SSE played a good role to send the data continuously without waiting to load in memory at once.

Websocket can be also used for this purpose but here we dont want duplex channel hence SSE played a vital role.

Collapse
 
zakariachahboun profile image
zakaria chahboun

Thanks for sharing your experience!

Collapse
 
andrewrhyand profile image
Andrew Rhyand

Using SSE as been a new pattern for me. After using tools like HTMX, I feel in love with sending back fragments of HTML.

Then I found Datastar data-star.dev/

It's a blend of JS signals, HTMX, and SSE.

Collapse
 
zakariachahboun profile image
zakaria chahboun

Have you used it in a real project? I mean "Data star"?

Collapse
 
andrewrhyand profile image
Andrew Rhyand

Internal tools only. It's still in beta with v1 on the horizon.

Collapse
 
dansasser profile image
Daniel T Sasser II

πŸ‘

Collapse
 
lovestaco profile image
Athreya aka Maneshwar

Pretty solid, btw how did you create the blog image?

Collapse
 
zakariachahboun profile image
zakaria chahboun

Thanks man! For the cover it's just AI generated.

Collapse
 
codesushil profile image
Code With Sushil

thanks man

Collapse
 
zakariachahboun profile image
zakaria chahboun

You're welcome man!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.