Lesson 9 / 30
Route Handlers & Status Codes
Write effective handlers and control HTTP response codes.
Async handlers return data
Fastify handlers are async functions. Return an object and Fastify auto-serializes it to JSON and sends 200 OK.
Custom status codes
Use reply.code() or reply.status() to set a custom HTTP status before sending.
fastify.post('/items', async (req, reply) => {
const item = { id: 1, name: 'Widget' };
return reply.code(201).send(item);
});
fastify.get('/missing', async (req, reply) => {
return reply.code(404).send({ error: 'Not found' });
});
fastify.delete('/items/:id', async (req, reply) => {
return reply.code(204).send();
});Handler options (schema, auth, etc.)
Fastify routes accept an optional third argument with metadata—schema for validation, auth for permission checks.