npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

api-rate-monitor

v1.0.0

Published

A Node.js package that tracks API requests and generates usage statistics for Express applications

Downloads

20

Readme

📊 API Rate Monitor

API Rate Monitor License Node.js Express

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:

  1. Tracking every API request that passes through your Express application
  2. Collecting important metrics like response time, status codes, and user information
  3. Storing this data in MongoDB or in-memory (your choice)
  4. Generating statistics about your API usage patterns
  5. 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