Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

HTML Server-Sent Events

Posted in HTML Tutorial
Updated on Sep 03, 2024
By Mari Selvan
πŸ‘οΈ 28 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
HTML Server-Sent Events

Photo Credit to CodeToFun

πŸ™‹ Introduction

Server-Sent Events (SSE) is a technology that allows a server to push updates to a web application over a single, long-lived HTTP connection.

This is particularly useful for real-time updates, such as news feeds, live sports scores, or stock market data. SSE is a simple yet powerful alternative to other real-time communication methods like WebSockets.

❓ What Are Server-Sent Events?

Server-Sent Events (SSE) is a web technology where the server sends updates to the client as they happen, without the client explicitly requesting them. This allows for real-time data streams from the server to the client, making it ideal for applications that require live updates.

πŸ€” How Do Server-Sent Events Work?

SSE works over HTTP and uses a single persistent connection to send multiple updates to the client. The server sends a stream of text data encoded in a specific format, which the client can listen to and process as events. Unlike WebSockets, SSE is one-way, meaning data is only sent from the server to the client.

βš™οΈ Setting Up Server-Sent Events

To set up SSE on the server side, you need to set the Content-Type to text/event-stream and ensure the response is continuously flushed to the client.

Here’s an example using Node.js:

node.js
Copied
Copy To Clipboard
const http = require('http');

http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
  });

  setInterval(() => {
    res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
  }, 1000);
}).listen(8080);

πŸ‘ Receiving Events on the Client Side

On the client side, you can use the EventSource API to receive and process events sent by the server. Here’s how you can do it:

javascript
Copied
Copy To Clipboard
const eventSource = new EventSource('http://localhost:8080');

eventSource.onmessage = function(event) {
  console.log('New message:', event.data);
};

πŸ”ƒ Reconnecting Automatically

One of the key features of SSE is its ability to automatically reconnect if the connection is lost. The EventSource object will attempt to reconnect after a disconnection, making it reliable for unstable network conditions.

javascript
Copied
Copy To Clipboard
eventSource.onerror = function(event) {
  console.error('EventSource failed:', event);
};

πŸ“… Handling Different Event Types

SSE supports different event types, which can be specified using the event field in the server’s message. This allows you to handle multiple types of events separately on the client side.

javascript
Copied
Copy To Clipboard
// Server-side
res.write('event: customEvent\n');
res.write('data: This is a custom event\n\n');

// Client-side
eventSource.addEventListener('customEvent', function(event) {
  console.log('Custom event:', event.data);
});

πŸ” Security Considerations

While SSE is over HTTP, it is important to consider security, especially when dealing with sensitive data. Always use HTTPS for secure communication and validate incoming data to prevent injection attacks. Also, consider implementing CORS policies to control who can access your SSE streams.

πŸ“ Example

Here’s a complete example demonstrating SSE with a simple real-time clock:

HTML
Copied
Copy To Clipboard
<!DOCTYPE html>
<html>
<head>
  <title>Server-Sent Events Example</title>
</head>
<body>
  <h1>Real-Time Clock</h1>
  <div id="clock"></div>

  <script>
    const eventSource = new EventSource('http://localhost:8080');

    eventSource.onmessage = function(event) {
      document.getElementById('clock').textContent = event.data;
    };

    eventSource.onerror = function() {
      console.error('Connection error. Retrying...');
    };
  </script>
</body>
</html>

πŸŽ‰ Conclusion

Server-Sent Events offer a straightforward way to implement real-time updates in your web applications. By understanding how to set up and use SSE, you can build responsive applications that keep users updated with the latest information without needing to constantly poll the server.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy