- Published on
Server Sent Events in React
- Authors
- Name
- Alexander Kim
What is Server-Sent Events?
Server-Sent Events are a standard allowing a web page to get updates from a server automatically. Unlike WebSockets, SSE establishes a one-way channel from the server to the client, making it ideal for scenarios where the server frequently updates data while the client remains a passive listener.
Key Features of SSE
- Simple to Use: SSE works over standard HTTP and does not require any special protocols.
- Efficient: Designed for unidirectional communication, reducing the complexity involved in message handling.
- Built-in Reconnection: Automatic reconnection in case of connection loss, with the ability to send a last event ID.
- Text-based Data Format: Uses simple text-based data format, which is easy to handle and parse.
How to Use SSE in React
Setting up the Server
On the server side, you need to create an endpoint that responds to requests with the text/event-stream content type. This tells the browser that it's an SSE endpoint.
// Node.js example with Express
app.get('/events', function(req, res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
// Send events to client
setInterval(() => {
res.write('data: ' + JSON.stringify({ message: 'Hello from server!' }) + '\n\n');
}, 1000);
});
Here we are sending a message to the client every second using '/events' endpoint. The message is a JSON object with a message property.
Setting up the Client
In the web page, use the EventSource interface to connect to the server. This interface automatically manages the connection and allows you to listen to messages from the server.
useEffect(() => {
const eventSource = new EventSource("/events");
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
};
eventSource.onerror = (event) => {
console.log(event);
};
return () => {
eventSource.close();
};
}, []);
Here we are using the useEffect hook to connect to the server when the component mounts. The onmessage event handler is called whenever the server sends a message. The onerror event handler is called when there is an error in the connection. Finally, we close the connection when the component unmounts.
Common Use Cases
SSE is a great choice for scenarios where the server frequently updates data while the client remains a passive listener. Some of the common use cases include:
- Real-Time Notifications: Automatically update clients with notifications or alerts.
- Stock Price Updates
- Live Feeds: Ideal for live news feeds, sports scores, etc.
- Monitoring Dashboards
Conclusion
Server-Sent Events offer a straightforward and efficient way for server-to-client communication. By leveraging SSE, developers can build highly responsive and real-time web applications without the complexity of more intricate technologies like WebSockets. Whether you're building a live news feed or a real-time notification system, SSE is a tool worth considering for its simplicity and efficiency.