Fastify

Fastify Tutorial

Halt rate limits as a Fastify preHandler hook.

The Fastify adapter ships in v0.4.0. It plugs in as a preHandler hook so limits run before your route handlers, with standard RateLimit-* headers and a 429 response on block.

1. Installation

npm install halt-rate fastify

2. Basic setup

import Fastify from 'fastify';
import { RateLimiter, InMemoryStore, presets } from 'halt-rate';
import { haltHook } from 'halt-rate/fastify';

const limiter = new RateLimiter({
  store: new InMemoryStore(),
  policy: presets.PUBLIC_API,
});

const app = Fastify({ logger: true });
app.addHook('preHandler', haltHook({ limiter }));

app.get('/', async () => ({ message: 'Hello, rate-limited world!' }));

await app.listen({ port: 3000 });

3. Custom blocked response

app.addHook('preHandler', haltHook({
  limiter,
  onBlocked: (req, reply, decision) => {
    reply.code(429).send({
      error: 'too_many_requests',
      retryAfter: decision.retryAfter,
    });
  },
}));

4. Per-route limits

Build a second limiter with a stricter policy (e.g. presets.AUTH_ENDPOINTS) and register a separate hook scoped to those routes via a Fastify plugin:

const authLimiter = new RateLimiter({
  store,
  policy: presets.AUTH_ENDPOINTS,
});

app.register(async (instance) => {
  instance.addHook('preHandler', haltHook({ limiter: authLimiter }));
  instance.post('/login', loginHandler);
}, { prefix: '/auth' });