What are Server-Sent Events and Why Do You Need Them?
\n\nImagine: you open a website with currency exchange rates, and the dollar rate changes right before your eyes — without refreshing the page, without clicking any buttons. Or you are waiting for the result of processing a large file on the server, and suddenly a line appears: "70% complete". How does this work? One of the most elegant ways is Server-Sent Events (SSE).
\n\nSSE is a technology that allows the server to independently send data to the client at any moment, as soon as it becomes available. Unlike WebSocket, SSE works only in one direction — from the server to the client. But that is its superpower: it is incredibly simple, efficient, and perfectly suited for tasks where the client only needs to receive updates.
\n\nIn this article, we will explore how to use Server-Sent Events in JavaScript, write working code, and understand when SSE is the best choice, and when it is better to look towards WebSocket. Ready? Let's go!
\n\nHow Do Server-Sent Events (SSE) Work?
\n\nTechnically, SSE is simply an HTTP connection that the server does not close after sending the response. Instead, it sends data in chunks using a special format text/event-stream. The client (browser) listens to this connection via the EventSource object and generates events upon receiving each new message.
Here is what a typical server response looks like:
\n\ndata: {"message": "Hello!", "timestamp": 1700000000}\n\ndata: {"message": "New notification", "timestamp": 1700000001}\n\nEach message starts with data:, followed by a space and the content itself. Messages are separated by two newline characters \\n\\n. The server can also send identifiers (id:) and event types (event:), but the minimum set is data.
The client side is even simpler:
\n\nconst eventSource = new EventSource('/events');\n\neventSource.onmessage = (e) => {\n console.log('Data received:', e.data);\n};\n\neventSource.onerror = (e) => {\n console.error('Connection error', e);\n};\n\nThat's it! No complex handshakes, no libraries — the browser automatically reconnects on disconnection and handles connection loss. This is the main magic of Server-Sent Events.
\n\nSSE vs WebSocket: When to Choose What?
\n\nOften beginners think: "Since SSE is simpler, it is always better." But this is not the case. Each technology has its own niche. Let's compare.
\n\n| Characteristic | \nSSE | \nWebSocket | \n
|---|---|---|
| Data direction | \nServer → client only | \nBidirectional | \n
| Ease of implementation | \nVery simple (native browser) | \nModerate (library needed) | \n
| Automatic reconnection | \nBuilt-in | \nNeeds manual implementation | \n
| Browser support | \nAll modern browsers (except IE) | \n
Blogs
Working with Databases in Kotlin: PostgreSQL and MongoDBA Day in the Life of a Go Developer: Code, Microservices, and Production SilenceContainerizing Rust Applications with Docker: From Binary to ProductionBook RecommendationsRead also |