What are Server-Sent Events? 💡
Server-Sent Events is a technology that enables servers to push data to web clients over a single HTTP connection. It's a simple and efficient way to send real-time updates from the server to the browser. SSE is often compared to WebSockets, but it has some unique features that make it suitable for certain use cases.
How SSE Works 🔄
SSE uses a simple text-based protocol. The server sends a stream of text data to the client over a single HTTP connection. The client opens a connection to the server and keeps it open, allowing the server to send updates whenever they're available. The server specifies a content type of text/event-stream
in the response, and the data is sent as a series of events.
Here's an example of an SSE event:
data: Hello, world!
id: 1
- The
data
field contains the actual message. - The
id
field is optional but can be used for event identification or resynchronization.
Implementing SSE
Server-Side Implementation (Node.js)
Let's look at how to implement SSE on the server side using Node.js and Express:
import express from 'express';
const app = express();
const port = 3111;
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const sendEvent = (data) => {
res.write("data: "+ data + "\\n\\n");
};
// Simulate real-time updates
setInterval(() => {
const timestamp = new Date().toLocaleTimeString();
sendEvent("Server time: " + timestamp );
}, 1000);
});
app.get('/', (req, res) => {
res.send('Welcome to SSE! 🥳');
});
app.listen(port, () => {
console.log(\`App is live at http://localhost:\${port}\`);
});
Client-Side Implementation
The client can establish a connection using the EventSource
API:
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log('Received:', event.data);
// Handle the received data
// Update the UI or perform any other action
};
In this code snippet, we create a new EventSource
instance that connects to the server's SSE endpoint. When the server sends an event, the onmessage
callback is triggered, and you can handle the data as needed.
Use Cases 🌐
SSE is an excellent choice for several use cases:
Real-time Feeds: You can use SSE to implement real-time news feeds, social media updates, or sports scores.
Notifications: It's great for sending instant notifications to clients, such as chat messages or new email alerts.
Live Updates: SSE can be used to provide live updates of data, like stock prices or weather information.
Long-Polling Alternative: SSE is a more efficient alternative to long-polling, where the client repeatedly polls the server for updates.
Tips 💡
Here are some tips for working with SSE:
Error Handling: Handle errors and reconnect to the server if the connection is lost.
Retry Mechanism: Implement a retry mechanism to handle temporary network issues.
Keep-Alive: Use the
ping
field to keep the connection alive and detect when it's lost.Event IDs: Use the
id
field to keep track of events for resynchronization or deduplication.Security: Be cautious of security issues. Ensure that your SSE endpoint is secure and properly authenticated.
Top comments (1)
Playground: stackblitz.com/edit/stackblitz-web...