DEV Community

Sannu kumar
Sannu kumar

Posted on

I build @sannuk792/api-response-monitor

pleas share your suggestion on comment if u using it
@sannuk792/api-response-monitor
GIT HUB
LIVE PACKAGES
Production-ready monitoring middleware for Node.js backends and frontend APIs. Tracks latency, status, and health with zero-config defaults.

โœจ Features

Core

  • Single-line Integration: app.use(apiMonitor())
  • Standardized Responses: Consistent { success, data, meta } format
  • Request Tracing: Auto-generated requestId in every response
  • Flexible Destinations: Console, file, or external URL

Production-Ready (New in v2.0)

  • ๐ŸŽฏ Log Levels: debug, info, warn, error
  • ๐Ÿ” Request ID / Trace ID: Automatic request tracking
  • โšก Performance Mode: Minimal overhead for high-traffic apps
  • โš ๏ธ Slow Endpoint Detection: Real-time slow API warnings
  • ๐Ÿšจ Alerting System: Error rate & latency threshold alerts
  • ๐Ÿ”Œ Plugin Architecture: Extend with custom plugins
  • ๐Ÿ’พ Storage Adapters: MongoDB, PostgreSQL, Elasticsearch support

๐Ÿ“ฆ Install

npm install @sannuk792/api-response-monitor
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Quick Start

Basic Setup

const express = require('express');
const { setupApiMonitoring } = require('@sannuk792/api-response-monitor');

const app = express();
setupApiMonitoring(app);

app.get('/api/test', (req, res) => {
  res.json({ message: "Hello World" });
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Response Format

Every response is automatically wrapped:

{
  "success": true,
  "message": "ok",
  "data": { "message": "Hello World" },
  "meta": {
    "status": 200,
    "latency": "12.45ms",
    "requestId": "req_abc123xyz",  // ๐Ÿ‘ˆ Automatic tracing
    "timestamp": "2024-02-09T10:15:30.123Z"
  }
}
Enter fullscreen mode Exit fullscreen mode

โš™๏ธ Configuration

All Options

app.use(apiMonitor({
  // Core
  enabled: true,
  destination: 'console',  // 'console' | 'file' | 'url'

  // Log Levels
  logLevel: 'info',  // 'debug' | 'info' | 'warn' | 'error'

  // Request Tracing
  generateRequestId: true,
  requestIdHeader: 'x-request-id',

  // Performance
  mode: 'full',  // 'full' | 'minimal'
  samplingRate: 1.0,  // 0.0 to 1.0
  maxEventsPerSecond: 1000,
  maxBodySize: '1mb',  // Skip large payloads

  // Routes to ignore
  ignoreRoutes: ['/health', '/metrics', '/favicon.ico'],

  // Slow detection
  slowThreshold: 1000,  // ms
  slowDetectorEnabled: true,

  // Security
  redactFields: ['password', 'token', 'authorization'],
  sanitizeLogs: true
}));
Enter fullscreen mode Exit fullscreen mode

Options Reference

Option Type Default Description
enabled boolean true Enable/disable monitoring
logLevel string 'info' Minimum log level
mode string 'full' 'full' or 'minimal'
destination string 'console' Log destination
generateRequestId boolean true Auto-generate request IDs
maxBodySize string null Skip monitoring if exceeded
slowThreshold number 1000 Slow endpoint threshold (ms)
samplingRate number 1.0 Event sampling rate
ignoreRoutes string[] [] Routes to skip
redactFields string[] ['password'...] Fields to redact

๐Ÿ” Request ID / Trace ID

Every request gets a unique ID for debugging:

// Automatic in responses
meta: { requestId: "req_lq8x2k_abc123" }

// Access in your code
app.get('/api/orders', (req, res) => {
  console.log('Processing:', req.requestId);
  // Use for logging, tracing, debugging
});

// Pass from client for end-to-end tracing
fetch('/api/data', {
  headers: { 'x-request-id': 'my-custom-id' }
});
Enter fullscreen mode Exit fullscreen mode

โšก Performance Mode

For high-traffic applications, use minimal mode:

apiMonitor({
  mode: 'minimal',      // Only status + latency, no payload
  samplingRate: 0.1,    // Track 10% of requests
  maxEventsPerSecond: 100
})
Enter fullscreen mode Exit fullscreen mode

Minimal mode response:

{
  "success": true,
  "meta": { "status": 200, "latency": "5.23ms", "requestId": "..." }
}
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ Slow Endpoint Detection

Automatically detects slow APIs:

apiMonitor({
  slowThreshold: 500,  // 500ms threshold
  slowDetectorEnabled: true
})

// Console output:
// โš ๏ธ /api/orders avg latency 850ms (threshold: 500ms)
Enter fullscreen mode Exit fullscreen mode

Access slow endpoint stats:

const { getSlowDetector } = require('@sannuk792/api-response-monitor');
const detector = apiMonitor.getSlowDetector();

// Get all slow endpoints
console.log(detector.getSlowEndpoints());
// [{ endpoint: '/api/orders', avg: 850, count: 23 }]
Enter fullscreen mode Exit fullscreen mode

๐Ÿšจ Alerting System

Get notified when thresholds are exceeded:

apiMonitor({
  alerting: {
    errorRateThreshold: 0.1,    // Alert if >10% errors
    latencyThreshold: 1000,     // Alert if avg >1s
    webhook: 'https://slack.webhook.url/...',  // Send to Slack/Discord
    onAlert: (alert) => {
      console.log(`๐Ÿšจ ALERT: ${alert.message}`);
      // { type: 'error_rate', value: 0.15, threshold: 0.1, message: '...' }
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”Œ Plugin System

Extend functionality with plugins:

const { apiMonitor, slowQueryPlugin, tagPlugin } = require('@sannuk792/api-response-monitor');

app.use(apiMonitor({
  plugins: [
    slowQueryPlugin(500),           // Detect slow queries
    tagPlugin({ env: 'production' }) // Add custom tags
  ]
}));
Enter fullscreen mode Exit fullscreen mode

Built-in Plugins

Plugin Description
slowQueryPlugin(ms) Detect slow endpoints
filterPlugin(fn) Drop events based on condition
tagPlugin(tags) Add custom tags to events
rateLoggerPlugin(rpm) Log high-traffic endpoints
statusCodeFilterPlugin([codes]) Keep only specific status codes

Custom Plugin

const myPlugin = (event, config, context) => {
  event.customField = 'value';
  return event;  // Return null to drop event
};
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’พ Storage Adapters

Store logs to databases:

MongoDB

const { MongoClient } = require('mongodb');
const client = new MongoClient(uri);
const collection = client.db('logs').collection('api-logs');

apiMonitor({
  storageAdapter: {
    type: 'mongo',
    options: { collection }
  }
})
Enter fullscreen mode Exit fullscreen mode

PostgreSQL

const { Pool } = require('pg');
const pool = new Pool({ connectionString: '...' });

apiMonitor({
  storageAdapter: {
    type: 'postgres',
    options: { pool, table: 'api_logs' }
  }
})
Enter fullscreen mode Exit fullscreen mode

Elasticsearch

const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });

apiMonitor({
  storageAdapter: {
    type: 'elastic',
    options: { client, index: 'api-logs' }
  }
})
Enter fullscreen mode Exit fullscreen mode

In-Memory (Testing)

apiMonitor({
  storageAdapter: { type: 'memory', options: { maxSize: 1000 } }
})
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Š Dashboard Example

A ready-to-use React dashboard is included:

cd examples/dashboard-react
npm install
npm run dev
# Open http://localhost:3001
Enter fullscreen mode Exit fullscreen mode

Features:

  • Real-time stats display
  • Paginated log table
  • Filtering by endpoint, method, status
  • Slow endpoint alerts
  • Live mode toggle

๐ŸŒ Frontend Usage

monitorFetch

import { monitorFetch, onApiResponse } from '@sannuk792/api-response-monitor';

const fetchMon = monitorFetch(window.fetch);
const res = await fetchMon('/api/data');

onApiResponse(log => console.log('API Log:', log));
Enter fullscreen mode Exit fullscreen mode

monitorAxios

import axios from 'axios';
import { monitorAxios } from '@sannuk792/api-response-monitor';

const api = monitorAxios(axios.create({ baseURL: '/api' }));
await api.get('/orders');
Enter fullscreen mode Exit fullscreen mode

๐Ÿ›ก๏ธ Security

Sensitive fields are automatically redacted:

apiMonitor({
  redactFields: ['password', 'token', 'authorization', 'api_key', 'ssn'],
  sanitizeLogs: true  // Strip control characters
})
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Tests

npm test
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“œ License

MIT ยฉ sannuk792

Top comments (0)