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

cutz-redis-ratelimit

v1.0.2

Published

A library for API ratelimiting using Upstash and Redis.

Downloads

6

Readme

cutz-redis-ratelimit (1.0.1)

cutz-redis-ratelimit is a simple and efficient rate limiting library using Upstash Redis. It provides built-in methods for handling rate limiting, calculating retry times, and creating rate limit responses.

Installation

Install the package using npm:

npm i cutz-redis-ratelimit

Usage

Importing the Library

import { Ratelimit } from "cutz-redis-ratelimit";

Creating a Ratelimit Instance

Create an instance of the Ratelimit class by providing the necessary configuration options:

const ratelimit = new Ratelimit({
  url: process.env.UPSTASH_REDIS_URL ?? "",
  token: process.env.UPSTASH_REDIS_TOKEN ?? "",
  time: "10 s",
  maxRequests: 1,
  logging: true,                        // optional
  whitelist: ['127.0.0.1'],             // optional
  blacklist: ['203.0.113.1'],           // optional
  blacklistConfig: {                    // optional
    blockDuration: 7200 * 1000,
    message: "Your IP has been blacklisted.",
  },
});

Using the Ratelimit Instance

Use the ratelimit instance to limit requests based on the client's IP address:

import { NextResponse } from "next/server";
import { Ratelimit } from "cutz-redis-ratelimit";

const ratelimit = new Ratelimit({
  url: process.env.UPSTASH_REDIS_URL,
  token: process.env.UPSTASH_REDIS_TOKEN,
  windowSize: "10 s",
  maxRequests: 1,
});

export async function GET(req: Request) {
  const ip = req.headers.get("x-forwarded-for") ?? "";
  const { success, reset } = await ratelimit.limit(ip);

  if (!success) {
    const retryAfter = ratelimit.getRetryAfter(reset);
    return ratelimit.createRateLimitResponse(retryAfter);
  }

  try {
    return NextResponse.json(
      { message: "Request successful" },
      { status: 200 }
    );
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to do something...." },
      { status: 500 }
    );
  }
}

API

Ratelimit Class

Constructor

constructor(options: RatelimitOptions)
  • options: An object containing the following properties:
    • url: The Upstash Redis URL.
    • token: The Upstash Redis token.
    • time: The time duration for the ratelimit (e.g., "10 s").
    • maxRequests: The maximum number of requests allowed within the window.
    • logging: (Optional) Enable logging for debugging purposes.
    • whitelist: (Optional) An array of IP addresses to whitelist.
    • blacklist: (Optional) An array of IP addresses to blacklist.
    • blacklistConfig: (Optional) Configuration for blacklisted IPs, including block duration and message.

Methods

limit(ip: string): Promise<{ success: boolean; reset: number; }>

Limits the number of requests based on the client's IP address.

  • ip: The client's IP address.
  • Returns a promise that resolves to an object containing:
    • success: A boolean indicating whether the request is allowed.
    • reset: The timestamp when the rate limit will reset.
getRetryAfter(reset: number): number

Calculates the retry-after time in seconds.

  • reset: The timestamp when the rate limit will reset.
  • Returns the retry-after time in seconds.
createRateLimitResponse(retryAfter: number): Response

Creates a rate limit response with the appropriate headers.

  • retryAfter: The retry-after time in seconds.
  • Returns a Response object with a 429 status code and the retry-after header.
createBlacklistResponse(): Response

Creates a blacklist response with the appropriate message.

  • Returns a Response object with a 403 status code and the blacklist message.
updateConfig({ time, maxRequests }: { time: Duration; maxRequests: number }): void

Updates the rate limit configuration.

  • time: The new time duration for the rate limit.
  • maxRequests: The new maximum number of requests allowed within the window.

License

This project is licensed under the ISC License.