How to Create a Real-Time Chart with Chart.js and WebSockets

Wednesday, January 15, 2025

Real-time charts are a great way to visualize constantly changing data. In this tutorial, we’ll build a simple real-time chart using Chart.js and WebSockets.

Step 1: Setting up the project

First, let’s initialize a new project and install the required packages.

Language: bash
mkdir realtime-chart
cd realtime-chart
npm init -y
npm install express ws chart.js

Step 2: Creating the WebSocket server

Set up a WebSocket server to send data updates.

Language: bash
// server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

setInterval(() => {
  const data = {
    time: new Date().toLocaleTimeString(),
    value: Math.random() * 100,
  };
  
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(data));
    }
  });
}, 1000);

console.log('WebSocket server running on ws://localhost:8080');

Step 3: Building the frontend

Create an index.html file and include Chart.js for the visualization.

Language: html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Real-Time Chart</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <canvas id="realtimeChart" width="400" height="200"></canvas>
  <script>
    const ctx = document.getElementById('realtimeChart').getContext('2d');
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: [],
        datasets: [{
          label: 'Random Data',
          data: [],
          borderColor: 'rgba(75, 192, 192, 1)',
          borderWidth: 2,
        }],
      },
      options: {
        animation: false,
        scales: {
          x: { display: true },
          y: { display: true },
        },
      },
    });

    const socket = new WebSocket('ws://localhost:8080');
    
    socket.onmessage = event => {
      const { time, value } = JSON.parse(event.data);
    
      chart.data.labels.push(time);
      chart.data.datasets[0].data.push(value);
    
      if (chart.data.labels.length > 10) {
        chart.data.labels.shift();
        chart.data.datasets[0].data.shift();
      }
    
      chart.update();
    };
  </script>
</body>
</html>

Step 4: Running the application

  • Start the WebSocket server:
  • Language: bash
    node server.js
  • Open index.html in your browser, and you’ll see a real-time updating chart!
  • Key takeaways

    This example demonstrates how simple tools like Chart.js and WebSockets can power real-time data visualization. With a bit of customization, you can scale this to display any data stream relevant to your needs.