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

shield-guard

v1.3.2

Published

Advanced rate limiting middleware for Node.js applications with enterprise-grade features and flexible configuration options

Readme

Shield Guard 🛡️

Advanced rate limiting middleware for Node.js applications with enterprise-grade features and flexible configuration options.

✨ Key Features

  • 🚀 High Performance: Optimized for minimal latency and maximum throughput
  • 🔄 Distributed Rate Limiting: Seamless coordination across multiple nodes
  • 🎯 Smart Burst Handling: Intelligent traffic spike management
  • 🌍 Geolocation Protection: Block or allow requests based on country
  • 🕵️ Advanced Security: Proxy validation and user agent filtering
  • 📊 Detailed Monitoring: Comprehensive logging and analytics
  • 🎨 Flexible Configuration: Highly customizable for any use case
  • 🔌 Framework Agnostic: Works with Express, Fastify, Koa, and more
  • 💾 Multiple Storage Backends: Memory, Redis, MongoDB, and custom stores
  • 🛠️ Developer Friendly: TypeScript support and extensive documentation
  • Ban System: Temporary IP banning for excessive requests
  • 🔍 Request Analysis: Track and analyze request patterns
  • 🌐 CDN Support: Compatible with major CDN providers
  • 🔒 Rate Limit by Path: Different limits for different endpoints

📦 Installation

npm install shield-guard

🚀 Quick Start

import express from 'express';
import { ShieldGuard } from 'shield-guard';

const app = express();

const shield = new ShieldGuard({
  windowMs: 15 * 60 * 1000, // 15 minutes
  limit: 100,               // Limit each IP to 100 requests per window
  banTime: 30 * 60 * 1000, // Ban for 30 minutes after limit exceeded
  message: {
    error: true,
    status: 429,
    message: 'Too many requests',
    details: {
      limit: 100,
      windowInMinutes: 15
    }
  }
});

app.use(shield.middleware());

🛠️ Advanced Configuration

Ban System Configuration

const shield = new ShieldGuard({
  windowMs: 15 * 60 * 1000,
  limit: 100,
  banTime: 60 * 60 * 1000, // 1 hour ban
  onBan: async (req, res) => {
    await logBannedIP(req.ip);
    res.status(403).json({
      error: 'IP banned',
      banExpiration: new Date(Date.now() + 60 * 60 * 1000)
    });
  }
});

Path-Specific Rate Limits

const shield = new ShieldGuard({
  windowMs: 60 * 1000, // 1 minute
  limit: (req) => {
    switch (req.path) {
      case '/api/auth':
        return 5;  // 5 login attempts per minute
      case '/api/search':
        return 30; // 30 searches per minute
      default:
        return 100; // Default limit
    }
  }
});

Advanced Security with Headers

const shield = new ShieldGuard({
  proxyValidation: true,
  blockByUserAgent: true,
  allowedUserAgents: ['Mozilla', 'Chrome', 'Safari', 'Edge'],
  headers: {
    remaining: 'X-RateLimit-Remaining',
    reset: 'X-RateLimit-Reset',
    total: 'X-RateLimit-Limit',
    retryAfter: 'Retry-After',
    banExpire: 'X-Ban-Expires'
  }
});

Redis Store with Clustering

const shield = new ShieldGuard({
  store: new RedisStore({
    client: redis.createCluster({
      nodes: [
        { host: 'localhost', port: 6379 },
        { host: 'localhost', port: 6380 }
      ]
    }),
    prefix: 'shield:',
    syncInterval: 1000
  }),
  distributed: true
});

Advanced Monitoring

const shield = new ShieldGuard({
  enableLogging: true,
  logLevel: 'info',
  logHandler: (log) => {
    console.log(`[${log.type}] IP: ${log.ip}`);
    console.log(`Path: ${log.path}`);
    console.log(`Rate: ${log.hits}/${log.limit}`);
    console.log(`User Agent: ${log.userAgent}`);
    if (log.banExpiration) {
      console.log(`Ban Expires: ${new Date(log.banExpiration)}`);
    }
  }
});

Dynamic Response Messages

const shield = new ShieldGuard({
  message: async (req) => {
    const timeLeft = await getRemainingTime(req.ip);
    return {
      error: true,
      code: 'RATE_LIMIT_EXCEEDED',
      message: 'Rate limit exceeded',
      details: {
        timeLeft: timeLeft,
        nextTry: new Date(Date.now() + timeLeft),
        path: req.path,
        method: req.method
      }
    };
  }
});

📊 Monitoring and Analytics

Shield Guard provides detailed metrics for monitoring:

  • Request counts per IP
  • Ban events and durations
  • Rate limit violations
  • Geographic distribution of requests
  • Response times and latency
  • Burst detection events

Prometheus Integration

const shield = new ShieldGuard({
  metrics: {
    enable: true,
    prometheus: true,
    prefix: 'shield_guard_',
    labels: ['path', 'method', 'status']
  }
});

🔧 API Reference

ShieldOptions

| Option | Type | Description | Default | |--------|------|-------------|---------| | windowMs | number | Time window for rate limiting | 60000 | | limit | number \| function | Request limit per window | 100 | | banTime | number | Ban duration in ms | 1800000 | | statusCode | number | HTTP status code | 429 | | message | string \| object \| function | Response message | 'Too many requests' | | headers | object | Custom headers | {} | | store | Store | Storage backend | MemoryStore | | distributed | boolean | Enable distribution | false | | burstLimit | number | Burst limit | 0 | | burstTime | number | Burst window | 1000 | | blockByCountry | boolean | Geo-blocking | false | | proxyValidation | boolean | Validate proxies | false | | enableLogging | boolean | Enable logging | false |

🌟 Best Practices

  1. Configure Ban System

    const shield = new ShieldGuard({
      banTime: 30 * 60 * 1000,
      onBan: async (req) => {
        await notifyAdmin(req.ip);
      }
    });
  2. Use Custom Storage for Production

    const shield = new ShieldGuard({
      store: new RedisStore(),
      distributed: true,
      syncInterval: 1000
    });
  3. Implement Path-Specific Limits

    const shield = new ShieldGuard({
      limit: (req) => {
        return req.path.startsWith('/api') ? 50 : 100;
      }
    });
  4. Enable Comprehensive Logging

    const shield = new ShieldGuard({
      enableLogging: true,
      logLevel: 'info',
      logHandler: customLogHandler
    });

📝 License

MIT © Shield Guard Contributors