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

@edgefirst-dev/worker-kv-rate-limit

v1.0.0

Published

A Rate Limit based on Cloudflare's Worker KV.

Downloads

362

Readme

@edgefirst-dev/worker-kv-rate-limit

A Rate Limit based on Cloudflare's Worker KV.

This class is based on Cloudflare's own Rate Limit feature currently in beta and only available to Cloudflare Workers.

This package can be used on your Cloudflare Pages application too as it uses Worker KV to keep the rate limit state.

Installation

Install from npm or GitHub Package Registry with;

bun add @edgefirst-dev/worker-kv-rate-limit

Usage

import { WorkerKVRateLimit } from "@edgefirst-dev/worker-kv-rate-limit";

export default {
  async fetch(request, env): Promise<Response> {
    let { pathname } = new URL(request.url);

    let rateLimit = WorkerKVRateLimit(env.KV);

    // key can be any string of your choosing
    let { success } = await rateLimit.limit({ key: pathname });

    if (!success) {
      return new Response(`429 Failure – rate limit exceeded for ${pathname}`, {
        status: 429,
        headers: await rateLimit.writeHttpMetadata({
          key: pathname,
          resource: "resource identifier", // Optional
        }),
      });
    }

    return new Response(`Success!`, {
      status: 200,
      headers: await rateLimit.writeHttpMetadata({
        key: pathname,
        resource: "resource identifier", // Optional
      }),
    });
  },
} satisfies ExportedHandler<Env>;

The limit function works exactly like Cloudflare's own Rate Limit feature. It returns an object with a success property that is true if the rate limit has not been exceeded and false if it has.

The writeHttpMetadata function returns an object with the necessary headers to be set on the response to the client. This is necessary to inform the client of the rate limit status.

If you want to apply extra headers, you can either keep the result Headers object and append headers there.

let headers = await rateLimit.writeHttpMetadata({
  key: pathname,
  resource: "resource identifier", // Optional
});
headers.set("X-Extra-Header", "Extra Value");

Or you can pass a Headers object to the writeHttpMetadata function and it will append the necessary headers to it.

let headers = new Headers();
headers.set("X-Extra-Header", "Extra Value");

await rateLimit.writeHttpMetadata(
  {
    key: pathname,
    resource: "resource identifier", // Optional
  },
  headers
);

The writeHttpMetadata will set the following headers:

  • X-RateLimit-Limit: The maximum number of requests allowed in the current window.
  • X-RateLimit-Remaining: The number of requests remaining in the current window.
  • X-RateLimit-Used: The number of requests used in the current window.
  • X-RateLimit-Reset: The time in seconds when the rate limit window resets.
  • X-RateLimit-Resource: The resource being rate limited (if provided).
  • Retry-After: The time in seconds when the rate limit window resets.

The X-RateLimit-Reset and Retry-After headers are the same and represent the time in seconds when the rate limit window resets, the reason to duplicate them is to keep compatibility with the Retry-After header that is used by the HTTP standard and consistency with common X-RateLimit- headers.

License

See LICENSE

Author