api-rate-monitor v1.0.0
๐ API Rate Monitor
A powerful Node.js package that tracks API requests and generates comprehensive usage statistics for your Express applications.
๐ What is API Rate Monitor?
API Rate Monitor is a lightweight middleware for Express.js applications that helps you understand how your APIs are being used. It works by:
- Tracking every API request that passes through your Express application
- Collecting important metrics like response time, status codes, and user information
- Storing this data in MongoDB or in-memory (your choice)
- Generating statistics about your API usage patterns
- Providing a dashboard where you can visualize and analyze this data
This gives you valuable insights into:
- Which endpoints are most frequently used
- Who your most active users are
- How your API performance changes over time
- Potential security issues (like unusual request patterns)
- Where to focus optimization efforts
Whether you're running a public API, a microservice architecture, or just want to understand your application's usage better, API Rate Monitor provides the visibility you need without complex setup or performance overhead.
โจ Features
- ๐ Comprehensive Tracking - Monitor all API endpoints with detailed statistics
- ๐ User & IP Monitoring - Track request rates per user and IP address
- ๐ Detailed Reports - Generate daily and monthly API usage reports
- ๐ฅ๏ธ Beautiful Dashboard - Interactive admin dashboard with real-time statistics
- ๐พ Flexible Storage - Choose between MongoDB, in-memory, or custom storage
- ๐ Secure Access - Authentication for the admin dashboard
- ๐ Easy Integration - Simple setup with Express applications
- โก Performance Optimized - Minimal impact on your API response times
๐ค Why Use API Rate Monitor?
For Developers
- Debug with data: Identify which endpoints are causing errors or performing slowly
- Optimize resources: Focus your optimization efforts on the most frequently used endpoints
- Improve user experience: Understand usage patterns to make better design decisions
- Monitor in real-time: Catch issues as they happen with live monitoring
For Business & Product Teams
- Understand user behavior: See which features are most valuable to your users
- Make data-driven decisions: Use actual usage data to prioritize development efforts
- Track growth: Monitor API usage growth over time
- Identify power users: Discover your most active users and their behavior patterns
For Operations & Security Teams
- Detect anomalies: Identify unusual traffic patterns that might indicate security issues
- Plan capacity: Understand usage patterns to better plan for scaling
- Monitor SLAs: Track response times and availability
- Audit access: See who is accessing what and when
API Rate Monitor is designed to be simple to set up but powerful in the insights it provides, making it valuable for teams of all sizes.
๐ฆ Installation
npm install api-rate-monitor
# or
yarn add api-rate-monitor
๐ Quick Start
const express = require('express');
const { ApiRateMonitor } = require('api-rate-monitor');
// Create Express app
const app = express();
// Initialize API Rate Monitor
const apiMonitor = new ApiRateMonitor({
// MongoDB connection (optional)
mongoUri: 'mongodb://localhost:27017/api-monitor',
// Enable dashboard
enableDashboard: true,
dashboardSecret: 'your-secret-key'
});
// Apply API monitoring middleware
app.use(apiMonitor.middleware());
// Mount the dashboard router
app.use('/api-monitor', apiMonitor.getDashboardRouter());
// Your routes...
app.get('/api/users', (req, res) => {
res.json({ users: ['user1', 'user2'] });
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
console.log('Dashboard available at http://localhost:3000/api-monitor');
});
๐ Configuration Options
The ApiRateMonitor
constructor accepts the following options:
Option | Type | Default | Description |
---|---|---|---|
mongoUri | string | undefined | MongoDB connection string. If not provided, in-memory storage will be used. |
storage | StorageInterface | undefined | Custom storage implementation. |
windowMs | number | 60000 | Time window for rate limiting in milliseconds (1 minute). |
maxRequests | number | 100 | Maximum number of requests within the time window. |
trackIp | boolean | true | Whether to track IP addresses. |
trackUserAgent | boolean | true | Whether to track user agents. |
getUserId | function | undefined | Function to extract user ID from request. |
enableDashboard | boolean | false | Whether to enable the admin dashboard. |
dashboardPath | string | /api-monitor-dashboard | Path for the admin dashboard. |
dashboardSecret | string | undefined | Secret key for dashboard authentication. |
๐ฅ๏ธ Dashboard
The package includes a beautiful admin dashboard that provides insights into your API usage:
To enable the dashboard:
const apiMonitor = new ApiRateMonitor({
enableDashboard: true,
dashboardPath: '/api-monitor',
dashboardSecret: 'your-secret-key'
});
// Mount the dashboard router
app.use('/api-monitor', apiMonitor.getDashboardRouter());
The dashboard will be available at /api-monitor
and requires authentication with the secret key.
๐พ Storage Options
MongoDB Storage
By default, the package uses MongoDB for storage if a connection string is provided:
const apiMonitor = new ApiRateMonitor({
mongoUri: 'mongodb://localhost:27017/api-monitor'
});
In-Memory Storage
If no MongoDB connection is provided, the package will use in-memory storage:
const apiMonitor = new ApiRateMonitor();
// Uses in-memory storage by default
Custom Storage
You can implement your own storage by implementing the StorageInterface
:
import { StorageInterface, RequestLog, DailyStats, MonthlyStats } from 'api-rate-monitor';
class CustomStorage implements StorageInterface {
async saveRequest(log: RequestLog): Promise<void> {
// Implementation
}
async getDailyStats(date: string): Promise<DailyStats> {
// Implementation
}
async getMonthlyStats(month: string): Promise<MonthlyStats> {
// Implementation
}
async getTopEndpoints(limit?: number): Promise<Array<{endpoint: string, count: number}>> {
// Implementation
}
async getTopUsers(limit?: number): Promise<Array<{userId: string, count: number}>> {
// Implementation
}
async getTopIps(limit?: number): Promise<Array<{ip: string, count: number}>> {
// Implementation
}
}
// Use custom storage
const apiMonitor = new ApiRateMonitor({
storage: new CustomStorage()
});
๐ค User Identification
You can track requests by user ID by providing a function to extract the user ID from the request:
const apiMonitor = new ApiRateMonitor({
getUserId: (req) => {
// Extract user ID from JWT token
if (req.headers.authorization) {
const token = req.headers.authorization.split(' ')[1];
try {
const decoded = jwt.verify(token, 'your-secret-key');
return decoded.userId;
} catch (err) {
return null;
}
}
// Or from session
return req.session?.userId || null;
}
});
๐ Examples
Basic Express Application
const express = require('express');
const { ApiRateMonitor } = require('api-rate-monitor');
const app = express();
const apiMonitor = new ApiRateMonitor();
app.use(apiMonitor.middleware());
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello World!' });
});
app.listen(3000);
With Authentication
const express = require('express');
const { ApiRateMonitor } = require('api-rate-monitor');
const jwt = require('jsonwebtoken');
const app = express();
const apiMonitor = new ApiRateMonitor({
getUserId: (req) => {
// Extract user ID from JWT token
if (req.headers.authorization) {
const token = req.headers.authorization.split(' ')[1];
try {
const decoded = jwt.verify(token, 'your-secret-key');
return decoded.userId;
} catch (err) {
return null;
}
}
return null;
}
});
app.use(apiMonitor.middleware());
// Your routes...
app.listen(3000);
Check out the examples directory for more usage examples.
๐งช Testing
# Run tests
npm test
# Run the example application
cd examples
node run-example.js
๐ License
MIT ยฉ API Rate Monitor
4 months ago