JavaScript: how to use Server-Sent Events (SSE) to monitor a cloud instance

JavaScript: how to use Server-Sent Events (SSE) to monitor a cloud instance

This article will explore how to implement this functionality using a combination of Node.js backend and React frontend.

In a modern development environment, real-time monitoring of a cloud instance deployment is crucial to ensure that everything is running smoothly and to react quickly to any issues. Using Server-Sent Events (SSE) in the frontend is an efficient way to get real-time updates from the server. This article will explore how to implement this functionality using a combination of Node.js backend and React frontend.

What are Server-Sent Events (SSE)?

SSE is a technology that allows the server to send automatic updates to the browser. Unlike WebSocket, which provides bidirectional communication, SSE is unidirectional: the server sends data to the client, but not the client sends data to the server. This makes it ideal for applications where the client needs to be updated frequently on new events, such as when monitoring a deployment.

Backend Implementation with Node.js

First, let's set up a simple Node.js server that will send SSE events to the frontend.


const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

// Simulate the deployment process
app.get('/deploy', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

// Simulate sending events at regular intervals
const deploySteps = [
  'Deployment started...',
  'File upload...',
  'Environment setup...',
  'Script execution...',
  'Checking integrity...',
  'Deployment completed!'
];

let stepIndex = 0;

const interval = setInterval(() => {
  if (stepIndex < deploySteps.length) {
    res.write(`data: ${deploySteps[stepIndex]}\n\n`);
    stepIndex++;
  } else {
    clearInterval(interval);
    res.end();
  }
}, 2000); // Send an event every 2 seconds

  req.on('close', () => {
    clearInterval(interval);
  });
});

app.listen(PORT, () => {
  console.log(`Server started on http://localhost:${PORT}`);
});

Frontend Implementation with React

Now, let's create a React application that connects to our SSE endpoint and displays messages in real time.


import { useEffect, useState } from 'react';

function DeployMonitor() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const eventSource = new EventSource('http://localhost:3000/deploy');

    eventSource.onmessage = (event) => {
    setMessages((prevMessages) => [...prevMessages, event.data]);
  };

  eventSource.onerror = () => {
    console.error('Error in SSE connection');
    eventSource.close();
  };

  return () => {
    eventSource.close();
  };
}, []);

return (
<div>
  <h1>Deploy Monitoring</h1>
  <ul>
    {messages.map((msg, index) => (
      <li key={index}>{msg}</li>
    ))}
  </ul>
</div>
);
}

export defaultDeployMonitor;

Benefits of SSE

  1. Simplicity: SSE is easier to implement than WebSocket for one-way use cases.
  2. Compatibility: SSE is well supported by modern browsers.
  3. Efficiency: It keeps an open connection to send data, reducing the load on repeated HTTP requests.

Conclusion

Monitoring the deployment of a cloud instance in real time is essential for effective management of modern applications. Using Server-Sent Events (SSE) allows you to get continuous and timely updates, improving the responsiveness of the development team and the quality of service. With the described implementation, you can easily monitor your deployments directly from the frontend, ensuring a smooth transition and no surprises.