Full answer
Fastify is a web framework focused on speed and structure. Its request lifecycle is explicit:
- Routing finds the route.
- onRequest hook: first chance to look at the request (authentication, request ids).
- preParsing: access to the raw payload stream before parsing.
- Body parsing by content type (JSON by default).
- preValidation: before the schema check.
- Validation: the route schema checks body, querystring, params and headers. A failure answers 400 with a message.
- preHandler: authorization, loading data that the handler needs.
- The handler. It can return a value (or a promise) or use reply.send().
- preSerialization: change the payload before it is turned into JSON.
- onSend: change the final string or buffer, set headers.
- onResponse: after the response is sent, good for metrics.
- onError and onTimeout fire in failure cases.
Hooks can be async functions. Throwing an error, or sending a reply, in a hook ends the chain.
Schemas: Fastify compiles JSON Schema with Ajv for validation and with fast-json-stringify for output. A response schema both speeds up serialization and acts as a filter: properties not in the schema (such as a password hash) are dropped.
Testing is easy with fastify.inject(), which simulates a request without opening a port, returning statusCode, headers and body.
Compared with Express: Fastify is schema-first, has encapsulated plugins, and handles async handlers from the start. Express is smaller to learn and has more third-party middleware.
const Fastify = require('fastify');
async function main() {
const app = Fastify();
const order = [];
for (const name of ['onRequest', 'preParsing', 'preValidation', 'preHandler', 'preSerialization', 'onSend', 'onResponse']) {
app.addHook(name, async () => { order.push(name); });
}
app.post('/students', {
schema: {
body: {
type: 'object',
required: ['name', 'marks'],
properties: { name: { type: 'string', minLength: 1 }, marks: { type: 'integer', minimum: 0, maximum: 100 } },
},
response: {
201: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } } }, // other fields are dropped
},
},
}, async (request, reply) => {
order.push('handler');
reply.code(201);
return { id: 1, name: request.body.name, internalNote: 'never sent to the client' };
});
const good = await app.inject({ method: 'POST', url: '/students', payload: { name: 'Asha', marks: 78 } });
await new Promise((resolve) => setTimeout(resolve, 10)); // let onResponse run
console.log('valid request:', good.statusCode, good.body);
console.log('hook order:', order.join(' > '));
const bad = await app.inject({ method: 'POST', url: '/students', payload: { name: 'Ravi', marks: 150 } });
console.log('invalid request:', bad.statusCode, '|', bad.json().message);
await app.close();
}
main();The response schema removes internalNote, and the invalid request never reaches the handler. Install first with npm install fastify (run here with fastify 5.12.8). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): valid request: 201 {"id":1,"name":"Asha"} hook order: onRequest > preParsing > preValidation > preHandler > handler > preSerialization > onSend > onResponse invalid request: 400 | body/marks must be <= 100
Key points
- Hooks run in a fixed order for every request.
- Schemas validate input and speed up and filter output.
- A hook that sends a reply ends the chain.
- inject() tests routes without a socket.
Common mistakes
- Putting authentication in preHandler when it should be earlier in onRequest.
- Using res or Express-style middleware signatures in Fastify hooks.
- Skipping response schemas and missing the speed and filtering benefits.
- Calling reply.send and also returning a value in an async handler.
Follow-ups
- How is Fastify validation different from validating inside the handler?
- How do you add a custom error handler?
- What does fastify.inject return?
Tips
- List the hooks in order from memory, or at least the main five.
- Say that response schemas can protect against data leaks.
- Mention inject for fast tests.