Custom Key Functions

Define custom key functions to rate limit by user ID, API key, or any other identifier.

Default Behavior

By default, hitlimit uses the client's IP address as the rate limit key.

hitlimit({
  limit: 100,
  window: '1m'
  // key defaults to (req) => req.ip
})

Rate Limit by User ID

Track rate limits per authenticated user instead of IP address.

hitlimit({
  limit: 100,
  window: '1m',
  key: (req) => req.user?.id || req.ip
})

Rate Limit by API Key

Use API keys from headers for per-client rate limiting.

hitlimit({
  limit: 1000,
  window: '1h',
  key: (req) => {
    const apiKey = req.headers['x-api-key'];
    return apiKey || req.ip;
  }
})

Composite Keys

Combine multiple identifiers for more granular rate limiting.

hitlimit({
  limit: 50,
  window: '1m',
  key: (req) => `${req.user?.id}:${req.method}:${req.path}`
})

Endpoint-Specific Limits

Apply different limits per endpoint by including the path in the key.

hitlimit({
  limit: 100,
  window: '1m',
  key: (req) => `${req.ip}:${req.baseUrl}`
})

Async Key Functions

Key functions can be async if you need to look up user data.

hitlimit({
  limit: 100,
  window: '1m',
  key: async (req) => {
    const user = await getUserFromToken(req.headers.authorization);
    return user?.organizationId || req.ip;
  }
})