Custom Response

Customize the 429 response body when a client exceeds the rate limit.

Default Response

By default, hitlimit returns a simple JSON error message.

{ "error": "Too many requests, please try again later." }

Static Response Object

Provide a custom object to return when rate limited.

hitlimit({
  limit: 100,
  window: '1m',
  response: {
    error: 'Rate limit exceeded',
    code: 'RATE_LIMITED',
    retryAfter: 60
  }
})

Dynamic Response Function

Use a function to generate a custom response with request context.

hitlimit({
  limit: 100,
  window: '1m',
  response: (req, info) => ({
    error: 'Too many requests',
    limit: info.limit,
    remaining: info.remaining,
    resetAt: info.reset,
    path: req.path
  })
})

Custom Status Code

Change the HTTP status code for rate limited responses.

hitlimit({
  limit: 100,
  window: '1m',
  statusCode: 503, // Service Unavailable
  response: {
    error: 'Service temporarily unavailable',
    retryAfter: 60
  }
})

HTML Response

Return HTML instead of JSON by using a handler function.

hitlimit({
  limit: 100,
  window: '1m',
  handler: (req, res) => {
    res.status(429).send(`
      <html>
        <body>
          <h1>Rate Limit Exceeded</h1>
          <p>Please try again later.</p>
        </body>
      </html>
    `);
  }
})

Response Info Object

The info parameter in response functions contains rate limit details.

PropertyTypeDescription
limitnumberMaximum requests allowed
remainingnumberRequests remaining (always 0 when limited)
resetnumberUnix timestamp when the window resets
retryAfternumberSeconds until the window resets