Lesson 9 / 32
Route Handlers & Status Codes
Write async route handlers, return objects as JSON and control status codes with reply.code.
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.