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

express-rate-shield

v1.0.0

Published

Custom Express rate limiter middleware in TypeScript to protect your APIs from excessive requests.

Readme

Express Rate Shield - Express Rate Limiting Middleware

A lightweight, high-performance rate limiting middleware for Express.js and Node.js applications. Protect your APIs from abuse with configurable request throttling per IP address.

Overview

express-rate-shield is a simple yet powerful TypeScript-based rate limiting solution designed to prevent API abuse, DDoS attacks, and excessive requests. It tracks incoming requests by IP address and enforces rate limits with minimal overhead.

Key Features

  • Lightweight & Fast - Minimal memory footprint with efficient IP tracking
  • 🔒 Secure - Prevents abuse and protects API endpoints from excessive requests
  • 🎯 Easy Integration - Simple Express.js middleware setup
  • 📊 Rate Limit Headers - Standard HTTP headers (X-RateLimit-*) for client transparency
  • 🌍 Proxy Support - Respects X-Forwarded-For headers for proxy environments
  • 💾 Auto Cleanup - Automatic memory management with timestamp cleanup
  • 🧪 TypeScript Ready - Full TypeScript support with type definitions

Installation

npm install express-rate-shield

Or with yarn:

yarn add express-rate-shield

Quick Start

import express from "express";
import { rateLimiter } from "rate-limit";

const app = express();

// Create rate limiter: max 100 requests per 15 minutes
const limiter = new rateLimiter({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // max 100 requests per window
  message: { error: "Too many requests, please try again later." },
});

// Apply to all routes
app.use(limiter.handler());

// Or apply to specific routes
app.get("/api/data", limiter.handler(), (req, res) => {
  res.json({ data: "your data" });
});

app.listen(3000);

Configuration Options

RateLimiterOptions

interface rateLimiterOptions {
  windowMs: number; // Time window in milliseconds
  max: number; // Max requests per window
  message?: message; // Custom error message
  headers?: boolean; // Enable/disable rate limit headers (default: true)
}

Parameters

| Parameter | Type | Default | Description | | ---------- | ------- | ------------------------------------------------ | ----------------------------------------------------------------- | | windowMs | number | required | Time window in milliseconds (e.g., 15 _ 60 _ 1000 for 15 minutes) | | max | number | required | Maximum number of requests allowed per time window | | message | object | { error: 'too many request please try again' } | Custom error response message | | headers | boolean | true | Include rate limit information in response headers |

Examples

Basic API Protection

import express from "express";
import { rateLimiter } from "express-rate-shield";

const app = express();
const apiLimiter = new rateLimiter({
  windowMs: 60 * 1000, // 1 minute window
  max: 30, // 30 requests per minute
});

app.use("/api/", apiLimiter.handler());

Strict Login Protection

const loginLimiter = new rateLimiter({
  windowMs: 15 * 60 * 1000, // 15 minute window
  max: 5, // Only 5 attempts per 15 minutes
  message: { error: "Too many login attempts, please try again later." },
});

app.post("/login", loginLimiter.handler(), (req, res) => {
  // Handle login
});

Custom Error Messages

const customLimiter = new rateLimiter({
  windowMs: 10 * 60 * 1000,
  max: 100,
  message: {
    error:
      "API rate limit exceeded. Please upgrade your plan for higher limits.",
  },
});

Disable Response Headers

const limiter = new rateLimiter({
  windowMs: 60 * 1000,
  max: 50,
  headers: false, // Disable X-RateLimit-* headers
});

Response Headers

When headers are enabled (default), the middleware adds the following headers:

  • X-RateLimit-Limit - Maximum requests per window
  • X-RateLimit-Remaining - Remaining requests in current window
  • Retry-After - Seconds to wait before retrying (when rate limit exceeded)

Error Responses

When rate limit is exceeded, the middleware returns:

{
  "status": 429,
  "message": "Too many requests, please try again later."
}

HTTP Status Code: 429 Too Many Requests

How It Works

  1. IP Detection - Identifies user IP from request (respects X-Forwarded-For for proxies)
  2. Request Tracking - Records request timestamps per IP address
  3. Window Validation - Checks if requests exceed limit in current time window
  4. Cleanup - Automatically removes old timestamps outside the window
  5. Response - Allows request to proceed or returns 429 status

Performance

  • Memory Efficient - Only stores IP addresses and timestamps
  • Automatic Cleanup - Expired timestamps are automatically removed
  • Fast Lookups - Uses JavaScript Map for O(1) lookups
  • Minimal Overhead - Minimal impact on request latency

Use Cases

  • ✅ Prevent API abuse and DDoS attacks
  • ✅ Protect login endpoints from brute-force attacks
  • ✅ Control resource consumption
  • ✅ Enforce API pricing tiers
  • ✅ Protect public endpoints from scraping
  • ✅ Implement fair usage policies

Proxy & Load Balancer Support

The middleware respects the X-Forwarded-For header, making it suitable for applications behind proxies and load balancers:

// Correctly identifies client IP through proxies
app.use(limiter.handler());

Best Practices

  1. Choose Appropriate Limits - Set limits based on expected traffic patterns
  2. Use Descriptive Messages - Help users understand rate limiting
  3. Monitor Usage - Track rate limit violations to detect attacks
  4. Combine Strategies - Use different limits for different endpoints
  5. Test Before Production - Verify limits don't block legitimate users

TypeScript Support

Full TypeScript support with exported types:

import { rateLimiter, rateLimiterOptions } from "rate-limit";

const options: rateLimiterOptions = {
  windowMs: 60 * 1000,
  max: 100,
};

const limiter = new rateLimiter(options);

License

See LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

Support

For issues, questions, or suggestions, please open an issue on the project repository.


rate-limit - Simple. Secure. Scalable rate limiting for Node.js and Express.js