Skip to content

Recipes ​

Limit One Path ​

Mounted with a path, the limiter counts only the requests below it, with its own quota; other routes stay unlimited.

ts
import { App, defineCoreHandler } from 'routup';
import { rateLimit } from '@routup/rate-limit';

export const app = new App();

// only requests below /auth count, 5 per minute
app.use('/auth', rateLimit({ windowMs: 60_000, max: 5 }));

app.post('/auth/login', defineCoreHandler(() => ({ ok: true })));
app.get('/', defineCoreHandler(() => 'Hello, World!'));

The sixth login attempt within a minute is rejected:

bash
curl -i -X POST http://localhost:3000/auth/login
# HTTP/1.1 429 Too Many Requests
# ratelimit-limit: 5
# ratelimit-remaining: 0
# retry-after: 60
#
# Too many requests, please try again later.

Tiered Quota ​

A max function returns the quota per request. Here API keys from a premium list get twice the default, and the key also identifies the client.

ts
import { App, defineCoreHandler, getRequestHeader } from 'routup';
import { rateLimit } from '@routup/rate-limit';

const PREMIUM_KEYS = new Set(['premium-key']);

export const app = new App();

app.use(rateLimit({
    // premium API keys get 10 requests per minute, everyone else 5
    max: (event) => (PREMIUM_KEYS.has(getRequestHeader(event, 'x-api-key') ?? '') ? 10 : 5),
    // count per API key, so one premium key does not share a quota with others
    keyGenerator: (event) => getRequestHeader(event, 'x-api-key') ?? 'anonymous',
}));

app.get('/', defineCoreHandler(() => 'Hello, World!'));
bash
curl -i -H 'x-api-key: premium-key' http://localhost:3000/
# ratelimit-limit: 10
curl -i -H 'x-api-key: free-key' http://localhost:3000/
# ratelimit-limit: 5

Count Only Failed Requests ​

With skipSuccessfulRequest, a request that ends below status 400 is uncounted after its response, so only failed logins use up the quota.

ts
import { App, defineCoreHandler, getRequestHeader } from 'routup';
import { rateLimit } from '@routup/rate-limit';

export const app = new App();

// only failed login attempts count towards the limit
app.use('/auth/login', rateLimit({
    max: 5,
    skipSuccessfulRequest: true,
}));

app.post('/auth/login', defineCoreHandler((event) => {
    if (getRequestHeader(event, 'authorization') !== 'Bearer valid-token') {
        event.response.status = 401;

        return { error: 'invalid_credentials' };
    }

    return { ok: true };
}));

A successful login is counted and uncounted again, so the quota stays untouched:

bash
curl -i -X POST -H 'authorization: Bearer valid-token' http://localhost:3000/auth/login
# HTTP/1.1 200 OK
# ratelimit-limit: 5
# ratelimit-remaining: 5

After five failed attempts the client is rejected until the window resets, also with the correct token: the request is counted before the route runs.

Count After the Response ​

A successful request is still counted while it runs, so slow requests that will be uncounted again, such as long-polls, can use up the quota. With countAfterResponse, a request is counted only once its response is known.

ts
import { App, defineCoreHandler, getRequestHeader } from 'routup';
import { rateLimit } from '@routup/rate-limit';

export const app = new App();

// only failed requests count, and only once their response is known:
// pending requests, such as long-polls, hold no slot
app.use('/api', rateLimit({
    max: 5,
    skipSuccessfulRequest: true,
    countAfterResponse: true,
}));

app.get('/api/events', defineCoreHandler((event) => {
    if (getRequestHeader(event, 'authorization') !== 'Bearer valid-token') {
        event.response.status = 401;

        return { error: 'invalid_credentials' };
    }

    return { events: [] };
}));

A successful request shows the quota before it and is never counted; each failed one is counted after its response:

bash
curl -i -H 'authorization: Bearer valid-token' http://localhost:3000/api/events
# HTTP/1.1 200 OK
# ratelimit-remaining: 5
curl -i http://localhost:3000/api/events
# HTTP/1.1 401 Unauthorized
# ratelimit-remaining: 4

The trade-off: concurrent failed requests are all let through until the first of them is counted, so a burst can exceed max (countAfterResponse).

Read the Limit State ​

useRequestRateLimitInfo() returns what the middleware counted for the current request.

ts
import { App, defineCoreHandler } from 'routup';
import { rateLimit, useRequestRateLimitInfo } from '@routup/rate-limit';

export const app = new App();

app.use(rateLimit({ max: 100 }));

app.get('/quota', defineCoreHandler((event) => {
    const info = useRequestRateLimitInfo(event);

    return {
        limit: info.limit,
        remaining: info.remaining,
        resetTime: info.resetTime,
    };
}));
bash
curl http://localhost:3000/quota
# {"limit":100,"remaining":99,"resetTime":"2026-01-01T00:01:00.000Z"}

resetTime is a Date, serialised as an ISO string; the value above is for a limiter started at midnight UTC, since MemoryStore windows count from that moment.

Custom Store ​

A store implements Store. This one gives every client its own window, starting with its first request, where MemoryStore resets all clients together.

ts
import { App, defineCoreHandler } from 'routup';
import type { IncrementResponse, Options, Store } from '@routup/rate-limit';
import { calculateNextResetTime, rateLimit } from '@routup/rate-limit';

type Entry = {
    hits: number;
    resetTime: Date;
};

/**
 * Gives every client its own window, starting with its first request.
 */
export class PerClientStore implements Store {
    windowMs = 60_000;

    entries = new Map<string, Entry>();

    init(options: Options) {
        this.windowMs = options.windowMs;
    }

    increment(key: string): IncrementResponse {
        let entry = this.entries.get(key);

        if (!entry || entry.resetTime.getTime() <= Date.now()) {
            entry = { hits: 0, resetTime: calculateNextResetTime(this.windowMs) };
            this.entries.set(key, entry);
        }

        entry.hits += 1;

        return { totalHits: entry.hits, resetTime: entry.resetTime };
    }

    decrement(key: string) {
        const entry = this.entries.get(key);

        if (entry && entry.hits > 0) {
            entry.hits -= 1;
        }
    }

    reset(key: string) {
        this.entries.delete(key);
    }
}

export const store = new PerClientStore();

export const app = new App();

app.use(rateLimit({
    windowMs: 60_000,
    max: 2,
    store,
}));

app.get('/', defineCoreHandler(() => 'Hello, World!'));

increment() may return a value or a promise, so the same shape works for a store that talks to a database.