Real-Time Dashboard with Live Data Updates

 Got it 👍 — Let’s design a small Real-Time Dashboard App where data updates live using Node.js, Express, Socket.IO, and MongoDB. This is the kind of mini advanced project you can finish in ~3 hours for a practical exam.


🚀 Example 5: Real-Time Dashboard with Live Data Updates


📂 Project Structure

realtime-dashboard/
│── src/
│   ├── config/
│   │   └── db.js
│   ├── controllers/
│   │   └── dataController.js
│   ├── models/
│   │   └── Metric.js
│   ├── routes/
│   │   └── dataRoutes.js
│   ├── app.js
│   └── server.js
│── public/
│   └── dashboard.html
│── .env
│── package.json

📦 Install Dependencies

npm init -y
npm install express mongoose socket.io cors dotenv morgan
npm install nodemon --save-dev

⚙️ src/config/db.js

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("✅ MongoDB Connected");
  } catch (err) {
    console.error("❌ MongoDB Error:", err.message);
    process.exit(1);
  }
};

module.exports = connectDB;

📊 src/models/Metric.js

const mongoose = require("mongoose");

const metricSchema = new mongoose.Schema({
  name: { type: String, required: true },
  value: { type: Number, required: true }
}, { timestamps: true });

module.exports = mongoose.model("Metric", metricSchema);

🎛️ src/controllers/dataController.js

const Metric = require("../models/Metric");

exports.createMetric = async (req, res, next) => {
  try {
    const { name, value } = req.body;
    const metric = await Metric.create({ name, value });
    
    // Emit update event to clients
    req.io.emit("metric_update", metric);

    res.status(201).json(metric);
  } catch (err) {
    next(err);
  }
};

exports.getMetrics = async (req, res, next) => {
  try {
    const metrics = await Metric.find().sort({ createdAt: -1 }).limit(10);
    res.json(metrics);
  } catch (err) {
    next(err);
  }
};

📡 src/routes/dataRoutes.js

const express = require("express");
const { createMetric, getMetrics } = require("../controllers/dataController");

const router = express.Router();

router.post("/", createMetric);
router.get("/", getMetrics);

module.exports = router;

🌍 src/app.js

const express = require("express");
const dotenv = require("dotenv");
const morgan = require("morgan");
const cors = require("cors");

const dataRoutes = require("./routes/dataRoutes");

dotenv.config();
const app = express();

app.use(cors());
app.use(express.json());
app.use(morgan("dev"));

app.use("/api/metrics", (req, res, next) => {
  req.io = app.get("io"); // inject socket instance
  next();
}, dataRoutes);

module.exports = app;

🖥️ src/server.js

const http = require("http");
const { Server } = require("socket.io");
const app = require("./app");
const connectDB = require("./config/db");

const PORT = process.env.PORT || 5000;

connectDB();

const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: "*" }
});

app.set("io", io);

io.on("connection", (socket) => {
  console.log("📡 New client connected:", socket.id);

  socket.on("disconnect", () => {
    console.log("❌ Client disconnected:", socket.id);
  });
});

server.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`));

🔑 .env

PORT=5000
MONGO_URI=mongodb://localhost:27017/realtime_dashboard

📊 public/dashboard.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real-Time Dashboard</title>
  <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
  <style>
    body { font-family: Arial; padding: 20px; }
    h2 { color: #333; }
    #metrics { margin-top: 20px; }
    .metric { padding: 10px; border-bottom: 1px solid #ddd; }
  </style>
</head>
<body>
  <h2>📊 Real-Time Metrics Dashboard</h2>
  <div id="metrics"></div>

  <script>
    const socket = io("http://localhost:5000");

    function addMetric(metric) {
      const div = document.createElement("div");
      div.classList.add("metric");
      div.innerHTML = `<b>${metric.name}</b>: ${metric.value}`;
      document.getElementById("metrics").prepend(div);
    }

    // Load initial metrics
    fetch("http://localhost:5000/api/metrics")
      .then(res => res.json())
      .then(data => data.forEach(addMetric));

    // Listen for updates
    socket.on("metric_update", (metric) => {
      addMetric(metric);
    });
  </script>
</body>
</html>

✅ Features

  1. API to create & fetch metrics (/api/metrics).

  2. WebSocket (Socket.IO) for real-time updates.

  3. Dashboard UI (HTML + JS) auto-updates without refresh.

  4. MongoDB persistence (metrics saved to DB).

  5. Lightweight, finishable in ~3 hours exam.


Extra Challenge (if time left):

  • Add chart.js or Recharts for live graphs 📈.

  • Role-based auth (Admin can add metrics, users only view).

  • Add multiple types of widgets (CPU, Memory, Sales, etc).


👉 Do you want me to also create a step-by-step 3-hour exam plan (like a timeline: 30min setup, 1h backend, 1h frontend, 30min polish) so you can practice under exam-like pressure?

Previous Post Next Post