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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongo-throttle

v1.3.0

Published

Basic IP rate-limiting middleware for Express stored in mongoDB. Use to throttle or limit incoming request rate.

Downloads

27

Readme

Mongo Throttle

Basic IP rate-limiting middleware for Express stored in MongoDB. Use to throttle or limit incoming request rate.

Let MongoDB do the heavy lifting and synchronization of throttling/rate-limiting requestors. This Express middleware registers and maintains a rate limit for each requesting IP address. It uses MongoDB's built-in expiration index to automatically sweep out expired Throttle records.

This rate-limiting implementation will scale across multiple servers with the same implementation.

Usage

var throttler = require('mongo-throttle');

// In Express-style app:
app.use(throttle());

// Optionally only rate-limit requests that begin with /api/
app.use('/api/', throttle());

// Optionally configure limits:
app.use(throttle({ rateLimit: { ttl: 600, max: 5 } }));

// Optionally configure a custom limit handler:
app.use(throttle(function(req, res, hits, remaining) {
    var until = new Date((new Date()).getTime() + remaining);
    res.statusCode = 420;
    res.send('You shall not pass ' + hits + ' until ' + until + '!');
}));

API

Headers

# Header fields set:
X-Rate-Limit-Limit      # Maximum requests within TTL
X-Rate-Limit-Remaining  # Requests remaining for IP
X-Rate-Limit-Reset      # msec until limit reset for IP

Configuration

// Configuration options/defaults:
{
    "rateLimit": {
        "ttl": 600      // TTL window for each IP limit
        "max": 600      // Max hits for IP within window
    },
    "response": {
        "code":    429, // Response code when limit is reached
        "message": "Rate Limit reached. Please wait and try again."
    },
    "mongoose":{
        "uri": false    // Optional Mongo URI connection string
    },
    "useCustomHeader": "x-custom-header" // Count hits by the distinct values found in this header, instead of by IP
}

// When using a custom limit handler:
/**
 * Custom Limit-reached handler
 *
 * @param {object} req          Express request
 * @param {object} res          Express response
 * @param {number} hits         Total hits for this IP within TTL
 * @param {number} remaining    msec reminaing before this IP resets TTL window
 */
function custom_limit(req, res, hits, remaining) {
    // handler response here
}

Models

// Upon registration, this middleware will create
// a Mongoose model collection with schema:
Throttle = {
    createdAt:   Date,
    ip:          String,
    hits:        Number
}

Install

npm install mongo-throttle [--save]

Acknowledgments/Notes

Mongo has a useful feature called a TTL index.

TTL collections make it possible to store data in MongoDB and have the mongod automatically remove data after a specified number of seconds or at a specific clock time.

You can tell Mongo to remove data for you! We will use this to remove expired request counts from our rate-limiting check. There are a couple important things to note about this feature:

  • As an index, it is set upon collection creation. If you want to change it, you'll have to do so manually.
  • The index-specific field, expireAfterSeconds, is in seconds. Unlike most other timestamps in your JavaScript code, don't divide this by 1000.

See Also

License

MIT