On this page

hitlimit() Function

Using Bun? See the Bun hitlimit() API for @joint-ops/hitlimit-bun.

The main function to create rate limiting middleware.

Function Signature

function hitlimit(options: HitlimitOptions): Middleware

Parameters

ParameterTypeRequiredDescription
optionsHitlimitOptionsYesConfiguration object

Options Object

PropertyTypeDefaultDescription
limitnumber100Max requests per window
windowstring | number'1m'Time window duration
key(req) => stringreq.ipKey extraction function
storeStorememoryStore()Storage backend
skip(req) => booleanundefinedSkip rate limiting
headersHeadersConfig-Rate limit response headers
responseobject | (info) => object-Custom error response body
tiersRecord<string, TierConfig>-Named tier configurations
tier(req) => string-Resolve tier name per request
banBanConfig-Auto-ban after repeated violations
onStoreError(error, req) => void-Handler when the store throws
logger{ warn(msg): void }-Logger for internal events
groupstring | (req) => string-Group identifier for shared limits

Return Value

Returns a middleware function compatible with Express, Fastify, Hono, and other frameworks.

type Middleware = (req: Request, res: Response, next: NextFunction) => void

Basic Example

import { hitlimit } from '@joint-ops/hitlimit'

// 100 requests per minute
const limiter = hitlimit({
  limit: 100,
  window: '1m'
})

Fastify Example

import Fastify from 'fastify'
import { hitlimit } from '@joint-ops/hitlimit/fastify'

const app = Fastify()

await app.register(hitlimit, {
  limit: 100,
  window: '1m'
})

Advanced Example

import { createHitLimit } from '@joint-ops/hitlimit/node'
import { redisStore } from '@joint-ops/hitlimit/stores/redis'

const limiter = createHitLimit({
  limit: 1000,
  window: '1h',
  key: (req) => req.headers['x-api-key'] || req.socket.remoteAddress,
  store: redisStore({ url: 'redis://localhost:6379' }),
  skip: (req) => req.url === '/health',
  headers: { standard: true, retryAfter: true },
  response: (info) => ({
    error: 'Rate limit exceeded',
    retryAfter: info.resetIn
  })
})

Error Handling

When rate limited, the middleware responds with:

HTTP/1.1 429 Too Many Requests
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 1640000060
Retry-After: 60

{ "error": "Too Many Requests" }