HTML SSE
In this page:
const source = new EventSource("url");
source.onmessage = (event) => { /* event.data */ };
What are Server-Sent Events?
Server-Sent Events (SSE) allow a webpage to receive real-time updates pushed automatically from a server. It uses a standard, one-way HTTP connection, making it simpler and more efficient than WebSockets for pushed updates.
Example: What are Server-Sent Events?
<script>
const source = new EventSource('/updates');
</script>
Connecting with EventSource
To start receiving Server-Sent Events, you initialize a new EventSource object inside your script, pointing to the server file that streams the updates.
Example: Connecting with EventSource
<script>
const source = new EventSource('/stream.php');
</script>
Listening for Message Events
Once your connection is active, you listen for pushed updates using the onmessage event, which captures the data sent from the server and lets you update your webpage content in real-time.
Example: Listening for Message Events
<script>
const source = new EventSource('/stream.php');
source.onmessage = function (event) {
console.log(event.data);
};
</script>
Auto-Reconnection Behaviors
If your network drops or your connection gets interrupted, the browser's EventSource object will automatically attempt to reconnect to the server in the background, keeping your connection stable without requiring manual scripts.
Example: Auto-Reconnection Behaviors
<script>
const source = new EventSource('/stream.php');
source.onerror = function () {
console.log('Connection lost, browser will retry automatically');
};
</script>
Server Stream Formatting
To stream events to a webpage, your server file must send a specific Content-Type header ('text/event-stream') and format its data output using a strict structure of 'data:' prefixes followed by double newlines.
Example: Server Stream Formatting
<!-- Server response headers: Content-Type: text/event-stream -->
<!-- Server response body: data: Hello\n\n -->
<script>
const source = new EventSource('/stream.php');
</script>
- Forgetting to send the required 'text/event-stream' Content-Type header from your server, causing connections to fail.
- Attempting to use SSE for two-way communication when WebSockets would be required.
- Omitting the double newline sequences in your server data outputs, preventing the browser from parsing updates.
- Server-Sent Events (SSE) allow servers to push real-time updates directly to webpages.
- Initiate connections inside your scripts using the EventSource object, and listen for updates using onmessage.
- Browsers handle connection drops and auto-reconnection natively, requiring zero custom fallback scripts.
Standard Server-Sent Events are supported natively by all modern web browsers.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: