Express.js Adapter

The Express adapter provides seamless integration with Express.js applications through middleware.

Installation

npm install @joint-ops/hitlimit
pnpm add @joint-ops/hitlimit
yarn add @joint-ops/hitlimit
bun add @joint-ops/hitlimit

Basic Usage

Use hitlimit as Express middleware:

app.ts
import express from 'express'
import { hitlimit } from '@joint-ops/hitlimit'

const app = express()

// Apply to all routes
app.use(hitlimit({
  limit: 100,
  window: '1m'
}))

app.listen(3000)

Route-Specific Rate Limiting

Apply different limits to specific routes:

routes.ts
const apiLimiter = hitlimit({
  limit: 100,
  window: '1m'
})

const authLimiter = hitlimit({
  limit: 5,
  window: '15m',
  message: 'Too many login attempts'
})

app.use('/api', apiLimiter)
app.use('/auth/login', authLimiter)

Custom Key Extraction

Rate limit by user ID, API key, or custom identifiers:

hitlimit({
  limit: 100,
  window: '1m',
  key: (req) => {
    // Rate limit by user ID if authenticated, otherwise by IP
    return req.user?.id || req.ip
  }
})

Skipping Requests

Bypass rate limiting for certain requests:

hitlimit({
  limit: 100,
  window: '1m',
  skip: (req) => {
    // Skip rate limiting for admins
    return req.user?.role === 'admin'
  }
})

Custom Error Response

Customize the response when rate limit is exceeded:

hitlimit({
  limit: 100,
  window: '1m',
  onLimit: (req, res) => {
    res.status(429).json({
      error: 'Rate limit exceeded',
      retryAfter: res.getHeader('Retry-After')
    })
  }
})

Using with Stores

Use Redis or SQLite for distributed rate limiting:

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

app.use(hitlimit({
  limit: 100,
  window: '1m',
  store: redisStore({
    url: 'redis://localhost:6379'
  })
}))

Next Steps