HttpProtect class

Per-IP request counting, rate limiting and banning for an express-like server.

Signature:

export default class HttpProtect 

Remarks

Counters and the block list live in Redis, so several processes behind a load balancer share one view of a client. Networks from @imqueue/net does the CIDR matching for HttpProtect.safeNetworks.

Constructing one opens a Redis connection unless HttpProtectOptions.redis supplies a client, and reads every threshold once — from the options, then from the environment. Changing an environment variable afterwards has no effect on a live instance.

The thresholds are not a rate. See HttpProtect.ttl for what the counter actually measures, and HttpProtectOptions.banLimit for how long a ban lasts, before putting this in front of real traffic.

Constructors

Constructor

Modifiers

Description

(constructor)(options)

Resolves every threshold, parses the exempt networks and connects to Redis.

Properties

Property

Modifiers

Type

Description

banLimit

readonly

number

The resolved ban threshold, from HttpProtectOptions.banLimit, HTTP_PROTECT_BAN_LIMIT, or 1000.

blockListKey

readonly

string

The Redis key of the block-list set, <prefix>:block-list.

getClientIp

readonly

(req: Request) => string | null

Resolves the client IP for a request — request-ip's getClientIp unless HttpProtectOptions.getClientIp replaced it.

maxRequests

readonly

number

The resolved 429 threshold, from HttpProtectOptions.maxRequests, HTTP_PROTECT_MAX_REQUESTS, or 200.

prefix

readonly

string

The resolved Redis key prefix, from HttpProtectOptions.redisPrefix.

safeNetworks

readonly

Networks

The parsed exempt networks, from HttpProtectOptions.safeNetworks.

ttl

readonly

number

The resolved idle timeout in seconds, from HttpProtectOptions.ttl, HTTP_PROTECT_TTL, or 10.

Methods

Method

Modifiers

Description

bannedNetworks()

The current block list, as a Networks object.

connect(options)

Opens a Redis connection and adopts it as this instance's client.

destroy()

Disconnects the Redis client and drops it.

isBanned(ip)

Whether an address is currently on the block list.

isLimited(ip)

Whether an address is currently over the 429 threshold.

jsonMiddleware()

A middleware that rejects with a JSON error body.

middleware()

A middleware that rejects with a bare status code and no body.

textMiddleware()

A middleware that rejects with text/plain.

verify(req)

Counts a request against its client IP and decides whether to serve it.

Read this page as plain markdown — no HTML, no navigation. For pasting into an LLM, or for an agent to fetch.