Skip to content

atharvakej/server-sent-events

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Server-Sent Events (SSE) Example

What are Server-Sent Events (SSE)?

Server-Sent Events (SSE) is a technology that allows a server to push real-time updates to the browser over a single, long-lived HTTP connection. Unlike traditional HTTP, where the client must repeatedly request updates (polling), SSE enables the server to send new data to the client whenever it becomes available.

How does SSE work?

  • The client (browser) creates an EventSource connection to a specific server endpoint.
  • The server responds with the Content-Type: text/event-stream header and keeps the connection open.
  • The server can send messages to the client at any time, using a simple text-based protocol.
  • The browser receives these messages as message events.

SSE vs WebSockets

Feature SSE (Server-Sent Events) WebSockets
Protocol HTTP (unidirectional) Custom (bidirectional)
Direction Server → Client only Server ↔ Client (full duplex)
Browser Support Most modern browsers All modern browsers
Complexity Simple (built-in EventSource) More complex (WebSocket API)
Reconnection Automatic (built-in) Manual (must handle yourself)
Use Cases Live feeds, notifications, logs Chat, games, collaborative apps
Binary Data No (text only) Yes (text and binary)
HTTP/2 Support Yes Not natively (needs upgrade)
Firewalls/Proxies Works well (HTTP) Sometimes blocked

Summary:

  • SSE is ideal for real-time, server-to-client updates (e.g., notifications, live dashboards).
  • WebSockets are better for interactive, two-way communication (e.g., chat, games).

How to Recreate This Example

1. Set up the server

  • Install dependencies:
    npm install express
  • Start the server:
    node index.js

2. Connect from the browser

  • Open your browser's developer console (F12).
  • Run the following code:
    let sse = new EventSource("http://localhost:8080/stream");
    sse.onmessage = console.log;
  • You will see a new message logged every second from the server.

References

About

Experiment with SSE using NodeJS

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published