Technical

Implementing Server-Sent Events (SSE)Using Python Flask & React


Ajackus logo in circle

Rahul Jain

Jan 21, 2025·5 mins read

IT Outsourcing | Ajackus.com
Table of Contents


    Share on:

    Real-time communication has emerged as a mainstay of the user experience for web applications. Live notifications, stock price updates, and other collaborative tools deliver up-to-the-second information to enhance interactivity and engagement. Traditional HTTP can get the job done for most use cases but fails when constant, real-time updates are the requirement. This is where Server-Sent Events (SSE) shine.

    Unlike WebSockets, which require bidirectional communication, SSE is a unidirectional protocol designed for streaming server-to-client updates in a lightweight and efficient manner. In this guide, we’ll explore the step-by-step implementation of SSE using Python Flask for the backend and React JS for the frontend.

    What Are Server-Sent Events (SSE)?

    This essentially gives the possibility for a server to push real-time updates to a client over a single, persistent HTTP connection. A client subscribes to the updates via an EventSource object, which listens for incoming data from the server.

    How SSE Works?

    Client Connection: The client establishes a connection to the server through the HTTP GET method. This will remain open as long as the server or client do not explicitly close it.
    Streamed Responses: The server is offering responses back to the client in a streaming format called text/event-stream, which has fields like data, event, and id to segregate the messages.
    Automatic Handling: Whenever there is a network interruption, the browser’s EventSource API automatically handles reconnections.

    Features of SSE:

    Basic HTTP-Based Protocol: No need to develop custom protocols and libraries. It works perfectly fine over standard HTTP/HTTPS.
    Auto-Reconnect: In the event of a network disconnection, the browser can attempt automatic reconnects, which aids in lesser development complexity.
    Lightweight: SSE is less resource-intensive than WebSockets because it doesn’t maintain a continuous two-way communication.
    Native Browser Support: The modern web browsers have started supporting SSE from the EventSource API, rendering any additional JS libraries unnecessary for using SSE.

    Why Choose SSE Instead of Other Alternatives?

    Although great for bidirectional communication, WebSockets feel like an overkill when updates only flow from the server to the client. For this kind of scenario, SSE is a much more straightforward and efficient answer. Also, SSE naturally works with HTTP/HTTPS, making it more easily integrable into an existing web infrastructure and more compatible with proxies and firewalls.

    When to Use SSE?

    Server-Sent Events are good at applications where the need is just for unidirectional, real-time updates.

    Here are more detailed use cases:

    Live Notifications:

    Email service, social networking sites, task management applications will all appreciate having real-time notifications. For example, Gmail utilizes SSE to tell a user there is a new email without them needing to refresh the page.
    SSE achieves a seamless user experience by delivering the instant update without much overhead.

    Real-Time Dashboards:

    Monitoring dashboards for server performance, application logs, or user analytics can use SSE to stream live data updates.
    For example, a server monitoring tool can display metrics like CPU usage, memory consumption, and active users in real-time using SSE.

    Stock Market Updates:

    Financial applications can push real-time stock price changes, cryptocurrency updates, or market news directly to the client.
    SSE offers an efficient and light mechanism to update high-frequency values without overloading the network.

    IoT Devices

    IoT systems, which may include smart home devices or industrial sensors, can stream temperature readings, machine status, or alerts to a central dashboard via SSE.
    Critical applications will require minimal latency as well as high response times

    Comparison of SSE with WebSockets

    While both SSE and WebSockets are designed for real-time communication, they serve different purposes. Let’s dive deeper into their differences:

    When to Use Each:

    Use SSE for applications like notifications, dashboards, and live feeds where data flows in one direction from the server to the client.
    Use WebSockets for applications like chat systems, collaborative tools, or multiplayer games, where two-way communication is essential.

    Building the Backend with Python Flask

    Step 1: Install Flask

    To start, you should have Flask and its dependencies installed. You can install Flask with pip:

    bash

    pip install flask flask-cors  

    Step 2: Flask App

    Here is a basic example of a Flask app that streams real-time updates:

    python

    from flask import Flask, Response, stream_with_context  

    import time  

    app = Flask(__name__)  

    @app.route(‘/events’)  

    def events():  

        def generate():  

            while True:  

                yield f”data: The current time is {time.ctime()}\n\n”  

                time.sleep(1)  

        return Response(stream_with_context(generate()), content_type=’text/event-stream’)  

    if __name__ == ‘__main__’:  

        app.run(debug=True, port=5000)  

    Explanation:

    • The /events endpoint streams data to the client.
    • The generate function uses a Python generator that yields new data every second. This ensures updates are sent incrementally without buffering.
    • The stream_with_context decorator is used to ensure that the generator functions correctly in the context of Flask’s request.
    • The content_type=’text/event-stream’ tells the client that the response is an SSE stream.

    Step 3: Add CORS Support

    If your frontend is hosted on a different domain or port, you’ll need to enable Cross-Origin Resource Sharing (CORS):

    bash

    pip install flask-cors  
    Python

    from flask_cors import CORS app = Flask(__name__) CORS(app)

    This allows the React frontend to connect to the Flask backend without cross-origin issues.

    Building the Frontend with React

    Step 1: Set Up React

    To create a React project, run:

    bash

    npx create-react-app react-sse  cd react-sse  

    Step 2: Retrieve data using EventSource

    Using a native EventSource API provided in the browser simplifies the ability to subscribe to SSE streams

    jsx

    import React, { useEffect, useState } from ‘react’;  const SSEComponent = () => {      const [messages, setMessages] = useState([]);      useEffect(() => {  

            const eventSource = new EventSource(‘http://localhost:5000/events’);  

            eventSource.onmessage = (event) => {  

                setMessages((prev) => […prev, event.data]);  

            };  

            eventSource.onerror = () => {  

                console.error(‘SSE connection error’);  

                eventSource.close();  

            };  

            return () => {  

                eventSource.close();  

            };  

        }, []);  

        return (  

            <div>  

                <h1>Real-Time Updates</h1>  

                <ul>  

                    {messages.map((msg, idx) => (  

                        <li key={idx}>{msg}</li>  

                    ))}  

                </ul>  

            </div>  

        );  

    };  

    export default SSEComponent;    

    Integrating SSE with Next.js

    For server-side rendering and API-based projects, Next.js provides seamless support for SSE:

    javascript

    export default function handler(req, res) {  

        res.setHeader(‘Content-Type’, ‘text/event-stream’);  

        res.setHeader(‘Cache-Control’, ‘no-cache’);  

        res.flushHeaders();  

        let counter = 0;  

        const interval = setInterval(() => {  

            res.write(`data: ${counter}\n\n`);  

            counter++;  

        }, 1000);  

        req.on(‘close’, () => {  

            clearInterval(interval);  

            res.end();  

        });  

    }  

    Advanced Topics in SSE

    1. Adding Authentication to SSE Streams

    Secure your endpoints by including a authentication token inside the client’s request headers. Validate this token on the server prior to streaming updates.

    2. Scaling Large Sites with Message Queues

    Message brokers, such as Redis or RabbitMQ, are to be used in high-traffic applications to manage updates that can be efficiently sent to multiple SSE streams.

    3. Streaming SSE with Frameworks

    Streaming SSE with frameworks like Next.js or HTMX is used for modern frontend workflows. As an example, Next.js API routes handle SSE endpoints quite easily.

    4. Handling Large Data Streams

    Keep the payload size optimized by sending only incremental updates, not the entire dataset, on each update.

    Conclusion

    Developers can leverage Server-Sent Events to build real-time applications without much complexity and overhead compared to alternatives like WebSockets. Whether creating a dashboard that shows live data, notification system, or monitoring application, SSE, paired with Python Flask and React, forms a solid solution.

    By following this guide, you’re ready to implement SSE, experiment with advanced features, and optimize your real-time web applications for a seamless user experience. You can also speak to us if you require any assistance on the same.

    Start a Project with Ajackus

    Start a Project with Ajackus

    You may also like

    left arrow
    Grey color right arrow