DEV Community

Cover image for express-insights: Your All-in-One Express Health Monitoring Middleware!
Mahmudur Rahman
Mahmudur Rahman

Posted on

express-insights: Your All-in-One Express Health Monitoring Middleware!

Hey developers! 👋 Tired of cobbling together tools for backend health monitoring? Meet express-insights, a production-ready Express middleware that bundles everything you need—system metrics, service checks, authentication, rate limiting, and a sleek HTML dashboard—all in one package! Powered by express, check-disk-space, dotenv, sanitize-html, validator, and winston, it’s your go-to solution for keeping tabs on your Node.js backend or integrating into an admin panel.

📅 Released: July 12, 2025

📦 npm: npm install express-insights

🌐 npm: NPM Package

📜 License: MIT


Why express-insights?

  • All-in-One: Combines express for routing, check-disk-space for disk stats, dotenv for env config, sanitize-html for secure HTML output, validator for input validation, and winston for robust logging.
  • Flexible Output: Get JSON for APIs or a responsive HTML dashboard for admin panels.
  • Smart Monitoring: Tracks CPU, memory, disk, and network with customizable alerts.
  • Secure: Supports authentication, rate limiting, and CORS.
  • Prometheus-Ready: Expose metrics for DevOps pipelines.
  • Plug-and-Play: Minimal setup for backend or admin panel integration.

Getting Started

Installation

Install the package and its dependencies in one go:

npm install express-insights

Enter fullscreen mode Exit fullscreen mode

This pulls in express, check-disk-space, dotenv, sanitize-html, validator, and winston, so you’re ready to roll!

Basic Setup

Add the middleware to your Express app:

const express = require('express');
const { healthCheck } = require('express-insights');

const app = express();

healthCheck(app, {
  route: '/health', // Endpoint
  htmlResponse: true, // Enable HTML dashboard
  style: 'dark', // Light or dark theme
  message: 'API Health Dashboard', // Custom title
  includeDisk: true, // Disk usage stats
  includeNetwork: true, // Network interface stats
  authentication: 'my-secret-key', // Secure the endpoint
  enableMetrics: true, // Prometheus metrics
  log: {
    level: 'info',
    destination: 'console',
  },
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000/health for JSON output or http://localhost:3000/health?html=true for the HTML dashboard (use Authorization: my-secret-key header).


Use Cases

1. Backend Health Monitoring

Monitor your server’s health directly via the /health endpoint. Get JSON output with system stats, service status, and metrics:

curl http://localhost:3000/health -H "Authorization: my-secret-key"

Enter fullscreen mode Exit fullscreen mode

Sample JSON Response:

{
  "status": "healthy",
  "uptime": "2d 1h 22m 17s",
  "version": "1.0.0",
  "environment": "production",
  "memory": {
    "heapUsed": "90 MB",
    "heapUsedPercent": "75.00%",
    "rss": "130 MB"
  },
  "system": {
    "platform": "linux",
    "memory": {
      "usedPercent": "75.00%",
      "alert": null
    },
    "loadavg": {
      "1min": "0.40",
      "alert": null
    }
  },
  "disk": {
    "total": "2000 MB",
    "used": "1200 MB",
    "free": "800 MB"
  }
}

Enter fullscreen mode Exit fullscreen mode

Use /health/metrics/prometheus for Prometheus-compatible metrics:

curl http://localhost:3000/health/metrics/prometheus

Enter fullscreen mode Exit fullscreen mode

Sample Prometheus Output:

# HELP health_check_requests_total Total health check requests
# TYPE health_check_requests_total counter
health_check_requests_total 18
# HELP health_check_response_time_ms Average response time in ms
# TYPE health_check_response_time_ms gauge
health_check_response_time_ms 134.25

Enter fullscreen mode Exit fullscreen mode

2. Admin Panel Integration

Integrate the health check into an admin panel with the HTML dashboard or fetch JSON data for custom UIs.

HTML Dashboard

Enable htmlResponse: true and visit /health or /health?html=true to see a responsive dashboard with system stats, service checks, and a raw JSON view. It’s perfect for quick status checks in an admin panel.

React Admin Panel

Fetch health data in a React app for a custom admin UI:

import { useEffect, useState } from 'react';

const HealthDashboard = () => {
  const [health, setHealth] = useState(null);

  useEffect(() => {
    fetch('http://localhost:3000/health', {
      headers: { Authorization: 'my-secret-key' },
    })
      .then((res) => res.json())
      .then((data) => setHealth(data))
      .catch((err) => console.error('Health check failed:', err));
  }, []);

  if (!health) return <p>Loading...</p>;

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial' }}>
      <h2>🚦 API Health Dashboard</h2>
      <p><strong>Status:</strong> {health.status}</p>
      <p><strong>Uptime:</strong> {health.uptime}</p>
      <p><strong>Memory:</strong> {health.memory.heapUsed} ({health.memory.heapUsedPercent})</p>
      <p><strong>CPU Load (1min):</strong> {health.system?.loadavg?.['1min']}</p>
      {health.disk && (
        <p><strong>Disk Usage:</strong> {health.disk.used} / {health.disk.total}</p>
      )}
    </div>
  );
};

export default HealthDashboard;

Enter fullscreen mode Exit fullscreen mode

Plain HTML + JS

For a lightweight admin panel, use plain JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Health Dashboard</title>
</head>
<body>
  <h2>🚦 API Health</h2>
  <pre id="output">Loading...</pre>
  <script>
    fetch('http://localhost:3000/health', {
      headers: { Authorization: 'my-secret-key' },
    })
      .then(res => res.json())
      .then(data => {
        document.getElementById('output').textContent = JSON.stringify(data, null, 2);
      })
      .catch(err => {
        document.getElementById('output').textContent = 'Error: ' + err.message;
      });
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Custom Service Checks

Monitor databases, Redis, or external APIs with custom checks:

const dbCheck = {
  name: 'database',
  timeout: 2000,
  retries: 2,
  check: async () => {
    const isAlive = await db.ping(); // Replace with your DB logic
    if (!isAlive) throw new Error('Database down');
    return true;
  },
};

healthCheck(app, {
  route: '/health',
  customChecks: [dbCheck],
});

Enter fullscreen mode Exit fullscreen mode

Failed checks mark services as unhealthy, affecting the overall status (degraded or unhealthy).


Secure and Scalable

  • Authentication: Secure with a static key or custom logic:

    authentication: (token) => token === 'Bearer secure123'
    
    
  • Rate Limiting: Prevent abuse:

    rateLimit: { windowMs: 10000, max: 5 } // 5 requests per 10s per IP
    
    
  • CORS: Restrict access to specific origins:

    cors: { allowedOrigins: ['https://admin.myapp.com'] }
    
    

    Or use environment variables:

    export ALLOWED_ORIGINS=https://admin.myapp.com,https://myapp.com
    
    

Try It Out!

  1. Install: npm install express-insights
  2. Set up the middleware with your desired config.
  3. Access /health for JSON or HTML output.
  4. Integrate into your admin panel or monitoring pipeline.
  5. Check Prometheus metrics at /health/metrics/prometheus.

express-insights - npm

Production-ready Express middleware for backend health monitoring with metrics, HTML/JSON output, authentication, and service checks.. Latest version: 1.0.0, last published: 2 minutes ago. Start using express-insights in your project by running `npm i express-insights`. There are no other projects in the npm registry using express-insights.

favicon npmjs.com

Happy monitoring! 🚀

Top comments (0)