SERVER-SENT EVENTS: Aprenda a Construir Sistemas que se Comunicam em Tempo Real
SSE vs. WebSockets: Choosing the Right Tool
While SSE excels at server-to-client updates, WebSockets offer bidirectional communication, making them suitable for complex applications like chats. However, WebSockets introduce higher complexity, require specialized infrastructure, and are not cacheable, whereas SSE is simpler, more efficient for unidirectional needs, and easier to implement.
Implementing SSE: Front-end and Back-end Essentials
Implementing SSE involves creating an `EventSource` object in the front-end to connect to a server endpoint. The back-end must set the `Content-Type` to `text/event-stream` and crucially, keep the response connection open, sending data with `data:` fields followed by double line breaks to delineate messages. Prematurely closing the response leads to polling behavior, not true SSE.
Advanced SSE: Event Naming and Formatting
Beyond basic data transmission, SSE supports event naming using the 'event' field. This allows clients to listen for specific types of events (e.g., 'transaction', 'log') rather than a generic message. The speaker demonstrates adding an 'event' field to the SSE response, which is then handled by an 'addEventListener' on the client-side, enabling more granular control and diverse real-time functionalities.
Production Considerations: Connection Management & Authentication
For production environments, managing client connections is crucial. The speaker emphasizes closing SSE connections when a client disconnects to prevent resource leaks. Furthermore, opening a new Redis connection for every SSE request is inefficient and can overload Redis; a Singleton pattern for a single, shared Redis connection is recommended. Authentication for SSE typically involves passing tokens via URL query parameters, as standard headers are not directly supported.



