Welcome to our comprehensive guide on JavaScript (JS) Server-Sent Events! In this tutorial, we'll explore what Server-Sent Events (SSE) are, why they're useful, and how to implement them in your projects. 📝
Server-Sent Events is a one-way communication technology between a web server and a web browser. It allows real-time streaming of data from the server to the client, making it ideal for applications that require live updates, such as stock tickers, chat apps, or real-time news feeds.
We'll start by creating a simple Node.js server that sends Server-Sent Events.
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/event-stream'});
setInterval(() => {
res.write(`data: ${new Date().toISOString()}\n\n`);
}, 1000);
});
server.listen(3000);Save this code in a file named server.js, then run it using Node.js.
Now, let's create an HTML page that connects to our SSE server and displays the data.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple SSE Client</title>
</head>
<body>
<h1>Real-time Updates with Server-Sent Events</h1>
<div id="updates"></div>
<script>
const source = new EventSource('http://localhost:3000');
source.onmessage = function(event) {
document.getElementById('updates').innerHTML += event.data + '<br>';
};
</script>
</body>
</html>Save this code in an index.html file, open it in your browser, and you should see real-time updates of the current date.
In real-world scenarios, you may need to handle multiple events at once. To do this, you can use the event.type property.
// Event handling for multiple events
source.onmessage = function(event) {
if (event.type === 'message') {
// Handle regular updates
document.getElementById('updates').innerHTML += event.data + '<br>';
} else if (event.type === 'error') {
// Handle error events
console.error(event.data);
}
};What is Server-Sent Events (SSE)?
Happy coding! 🎉