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
- Introduction
- What are Server-Sent Events?
- Key Benefits
- SSE Message Format
- Simple Code Examples
- SSE vs WebSockets
- Best Use Cases
- Pro Tips
- Conclusion
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
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)
}
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();
}
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 π―
- Live notifications
- Real-time dashboards
- Stock market updates
- Social media feeds
- Live sports scores
- System monitoring
Pro Tips π‘
- 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
- Reconnection Control: Set custom retry time:
retry: 5000\n\n
- Event IDs: Track message sequence:
id: 12345\n
data: Your message here\n\n
- 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
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)
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".
Server Sent Events are still not production ready after a decade. A lesson for me, a warning for you!
Mike Talbot β γ» Jun 6 '20
Cool, thanks for sharing! I will read it. π
True. I am still struggling to configure nginx properly for SSE
These are the headers I send
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!
Glad this post brought it to your attention! Do you think you'll use SSE in any of your projects?
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.
Not everything has to be taken so seriouslyβsometimes a catchy title is just that. Take it easy!
Click bait is always click bait.
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
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!
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!
Try it and tell us π
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
@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.
SSE is simplest described as a regular HTTP request with a streaming response; the streaming payload is events.
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.
Ok, go it
The server and client will keep this connection alive for future server-to-client event notifications.
Thanks! π
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.
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.
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.
Thanks for sharing your experience!
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.
Have you used it in a real project? I mean "Data star"?
Internal tools only. It's still in beta with v1 on the horizon.
π
Pretty solid, btw how did you create the blog image?
Thanks man! For the cover it's just AI generated.
thanks man
You're welcome man!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.