Node.js HTTP Adapter

The raw Node.js adapter works directly with the built-in http module without any framework.

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 with Node.js http server:

server.ts
import { createServer } from 'http'
import { hitlimitHandler } from '@joint-ops/hitlimit/node'

const limiter = hitlimitHandler({
  limit: 100,
  window: '1m'
})

const server = createServer(async (req, res) => {
  // Check rate limit
  const result = await limiter(req, res)

  if (result.limited) {
    return // Response already sent
  }

  // Handle request
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ message: 'Hello World' }))
})

server.listen(3000)

Middleware Style

Use the middleware-style handler for cleaner code:

server.ts
import { createServer } from 'http'
import { hitlimitMiddleware } from '@joint-ops/hitlimit/node'

const limiter = hitlimitMiddleware({
  limit: 100,
  window: '1m'
})

const server = createServer((req, res) => {
  limiter(req, res, () => {
    // Request passed rate limit check
    res.writeHead(200)
    res.end('OK')
  })
})

server.listen(3000)

Custom Key Extraction

Rate limit by custom identifiers:

const limiter = hitlimitHandler({
  limit: 100,
  window: '1m',
  key: (req) => {
    // Extract API key from header
    return req.headers['x-api-key'] || getClientIp(req)
  }
})

Custom Error Response

Customize the rate limit exceeded response:

const limiter = hitlimitHandler({
  limit: 100,
  window: '1m',
  onLimit: (req, res, info) => {
    res.writeHead(429, {
      'Content-Type': 'application/json',
      'Retry-After': String(info.resetIn)
    })
    res.end(JSON.stringify({
      error: 'Too many requests',
      retryAfter: info.resetIn
    }))
  }
})

Using with Stores

Use a persistent store for production:

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

const limiter = hitlimitHandler({
  limit: 100,
  window: '1m',
  store: redisStore({
    url: 'redis://localhost:6379'
  })
})

Accessing Rate Limit Info

Get detailed rate limit information:

const result = await limiter(req, res)

console.log(result)
// {
//   limited: false,
//   limit: 100,
//   remaining: 73,
//   reset: 1640000000
// }

Next Steps