पाठ 14 / 30

Middleware और Hooks Pattern

Logging, authentication, और rate limiting जैसे cross-cutting concerns को implement करें।

Middleware के बजाय hooks क्यों?

Fastify के hooks traditional middleware chains से अधिक explicit और performant हैं। हर hook के पास request lifecycle में एक स्पष्ट भूमिका है।

Hooks के साथ Logging middleware

आने वाले को log करने के लिए onRequest, outgoing को log करने के लिए onSend उपयोग करें।

fastify.addHook('onRequest', async (request, reply) => {
  request.startTime = Date.now();
});

fastify.addHook('onSend', async (request, reply, payload) => {
  const duration = Date.now() - request.startTime;
  fastify.log.info({
    method: request.method,
    url: request.url,
    statusCode: reply.statusCode,
    duration,
  });
  return payload;
});