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 🙏

© 2025 – Pkg Stats / Ryan Hefner

jmrashed-api-rate-limiter

v2.0.1

Published

Express middleware to control and protect APIs by enforcing configurable rate limits (per user, role, or API key) with extensible strategies.

Readme

Jmrashed API Rate Limiter

NPM Version NPM Downloads License GitHub stars GitHub forks GitHub issues

A flexible and lightweight middleware for Express.js that helps you protect your APIs from abuse and manage server load effectively. This package allows for dynamic rate limits based on user roles, API keys, or any other identifier, making it a versatile solution for any Node.js application.

Table of Contents

Features

  • Method-Based Rate Limiting: Set different rate limits for various HTTP methods (e.g., GET, POST, PUT, DELETE).
  • Configurable Time Windows: Define the duration for which requests are tracked (e.g., per minute, per hour).
  • Dynamic Limits: Implement custom logic to assign different limits to different users, roles, or API keys.
  • In-Memory Storage: A simple and fast in-memory store for tracking request counts, which can be extended for persistent storage solutions like Redis.
  • Lightweight and Performant: Designed to have minimal impact on your application's performance.

Prerequisites

Before you begin, ensure you have the following installed:

Installation

To install the Jmrashed API Rate Limiter, use npm:

npm install jmrashed-api-rate-limiter

Usage

Here’s how to integrate the middleware into your Express.js application:

const express = require('express');
const rateLimit = require('jmrashed-api-rate-limiter');

const app = express();
const PORT = process.env.PORT || 3000;

// Configure rate limiter options
const rateLimiterOptions = {
  windowMs: 60 * 1000, // 1 minute
  limits: {
    GET: 10,  // 10 requests per minute for GET
    POST: 5,  // 5 requests per minute for POST
    default: 15 // Default limit for other methods
  }
};

// Apply rate limiter middleware
app.use(rateLimit(rateLimiterOptions));

// Sample route
app.get('/api/resource', (req, res) => {
  res.send('Resource accessed!');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Configuration Options

  • windowMs (required): The duration of the rate-limiting window in milliseconds.
  • limits (required): An object defining the number of allowed requests for each HTTP method. You can also set a default limit for methods that are not explicitly defined.

Example of Dynamic Limits

To implement dynamic limits, you can modify the logic inside the middleware to use a unique identifier for each user, such as an API key or user ID. This allows you to apply different rate limits based on the user's plan or access level.

Here's an example of how you could modify the rateLimiter.js file to support dynamic limits based on a user's role:

// lib/rateLimiter.js

const rateLimit = (options) => {
  const { windowMs, limits } = options;
  const requestCounts = new Map();

  return (req, res, next) => {
    // Use the user's role as the key, or fall back to the IP address
    const key = req.user ? req.user.role : req.ip; 

    const currentTime = Date.now();

    if (!requestCounts.has(key)) {
      requestCounts.set(key, { count: 0, startTime: currentTime });
    }

    const requestData = requestCounts.get(key);

    if (currentTime - requestData.startTime > windowMs) {
      requestData.count = 0;
      requestData.startTime = currentTime;
    }

    // Define different limits for different roles
    const limitsByRole = {
      admin: 100,
      premium: 50,
      free: 10,
    };

    const limit = limitsByRole[key] || limits[req.method] || limits.default;

    if (requestData.count < limit) {
      requestData.count += 1;
      next();
    } else {
      res.status(429).json({
        error: "Too many requests. Please try again later.",
      });
    }
  };
};

module.exports = rateLimit;

Screenshots

Here are some screenshots of the rate limiter in action:

Successful Request:

Successful Request

Rate Limit Exceeded:

Rate Limit Exceeded

Testing

To run the tests for this package, use the following command:

npm test

You can also test the rate limiter manually using tools like Postman or curl. Make multiple requests to your API endpoints and observe how the middleware enforces the defined limits.

Deployment

When deploying an application that uses this middleware, ensure that your environment has Node.js and npm installed. You can then run your application using a process manager like PM2 or by simply running node your-app.js.

Built With

FAQ

Q: Can I use this with a different framework, like Koa or Hapi?

A: This middleware is specifically designed for Express.js. However, the core logic could be adapted for other frameworks.

Q: Is it possible to use a persistent storage solution instead of in-memory storage?

A: Yes, you can modify the rateLimiter.js file to use a different storage solution, such as Redis or a database. This is recommended for production environments.

Roadmap

  • [ ] Add support for more persistent storage solutions (e.g., Redis, Memcached).
  • [ ] Add more advanced configuration options (e.g., whitelisting IPs, custom headers).
  • [ ] Add support for more frameworks (e.g., Koa, Hapi).
  • [ ] Add more comprehensive tests.

Release Notes

2.0.1 - 2025-08-15

  • Documentation: Added release notes and updated README for clarity.
  • Improvements: Small improvements to dynamic limits examples and configuration docs.
  • Tests: Minor test coverage tweaks and reliability improvements.
  • Misc: Updated package metadata and README badges.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Contributing

We welcome contributions from the community. Please read our Contributing Guide for more information on how to get started.

Style Guide

This project follows the Airbnb JavaScript Style Guide. Please ensure that your contributions adhere to this style guide.

Code of Conduct

Please read our Code of Conduct before contributing.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

Author

Rashed Zaman

Feel free to reach out for questions, feedback, or contributions!