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
requestIdin 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
๐ 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);
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"
}
}
โ๏ธ 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
}));
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' }
});
โก 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
})
Minimal mode response:
{
"success": true,
"meta": { "status": 200, "latency": "5.23ms", "requestId": "..." }
}
โ ๏ธ Slow Endpoint Detection
Automatically detects slow APIs:
apiMonitor({
slowThreshold: 500, // 500ms threshold
slowDetectorEnabled: true
})
// Console output:
// โ ๏ธ /api/orders avg latency 850ms (threshold: 500ms)
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 }]
๐จ 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: '...' }
}
}
})
๐ 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
]
}));
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
};
๐พ 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 }
}
})
PostgreSQL
const { Pool } = require('pg');
const pool = new Pool({ connectionString: '...' });
apiMonitor({
storageAdapter: {
type: 'postgres',
options: { pool, table: 'api_logs' }
}
})
Elasticsearch
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
apiMonitor({
storageAdapter: {
type: 'elastic',
options: { client, index: 'api-logs' }
}
})
In-Memory (Testing)
apiMonitor({
storageAdapter: { type: 'memory', options: { maxSize: 1000 } }
})
๐ Dashboard Example
A ready-to-use React dashboard is included:
cd examples/dashboard-react
npm install
npm run dev
# Open http://localhost:3001
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));
monitorAxios
import axios from 'axios';
import { monitorAxios } from '@sannuk792/api-response-monitor';
const api = monitorAxios(axios.create({ baseURL: '/api' }));
await api.get('/orders');
๐ก๏ธ Security
Sensitive fields are automatically redacted:
apiMonitor({
redactFields: ['password', 'token', 'authorization', 'api_key', 'ssn'],
sanitizeLogs: true // Strip control characters
})
๐งช Tests
npm test
๐ License
MIT ยฉ sannuk792

Top comments (0)