Routing and request handling
Fifth chapter of the "Fastify with TypeScript" series. With app.ts and server.ts in place, it's time to build our first real routes. By the end of the chapter the project will have a users module that can create, read and list users, and we'll have met the three places a request carries data: route parameters, the query string and the body.
A module for the users
Each area of the application gets its own folder under src/. Create src/users/users.route.ts:
// src/users/users.route.ts
import type { FastifyInstance } from 'fastify';
export default async function userRoutes(fastify: FastifyInstance) {
fastify.get('/', async () => {
return [];
});
}
This file default-exports a plugin: an async function that receives the Fastify instance and declares routes on it. To use it, register it in src/app.ts. Add the import at the top of the file:
import userRoutes from './users/users.route.ts';
and, inside buildApp(), replace the three comment lines left from the previous chapter with:
app.register(userRoutes, { prefix: '/api/v1/users' });
The route is declared as / inside the plugin and the prefix is added in front of it, so the module doesn't need to know where it is mounted. With npm run dev running:
curl localhost:3000/api/v1/users
# []
Shorthand methods and full routes
fastify.get(), .post(), .put(), .patch() and .delete() are shorthands. Each takes a URL, an optional options object and a handler. The same route can be written in the longer form with fastify.route(), which is handy when the method or the URL come from a variable:
fastify.route({
method: 'GET',
url: '/',
handler: async () => {
return [];
},
});
The two forms are equivalent. This series uses the shorthands.
Params, query string, and body
Now let's make the module do something. Replace the content of src/users/users.route.ts with:
// src/users/users.route.ts
import type { FastifyInstance } from 'fastify';
interface User {
id: string;
name: string;
email: string;
}
export default async function userRoutes(fastify: FastifyInstance) {
// Temporary in-memory storage: PostgreSQL replaces it in chapter 13
const users: User[] = [];
// Query string: GET /api/v1/users?limit=10
fastify.get('/', async (request) => {
const { limit = '10' } = request.query as { limit?: string };
return users.slice(0, Number(limit));
});
// Route parameter: GET /api/v1/users/:id
fastify.get('/:id', async (request, reply) => {
const { id } = request.params as { id: string };
const user = users.find((u) => u.id === id);
if (!user) {
reply.code(404);
return { error: 'User not found' };
}
return user;
});
// Request body: POST /api/v1/users
fastify.post('/', async (request, reply) => {
const { name, email } = request.body as { name: string; email: string };
const user: User = { id: crypto.randomUUID(), name, email };
users.push(user);
reply.code(201);
reply.header('Location', `/api/v1/users/${user.id}`);
return user;
});
}
Try the three routes in order:
curl -i -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace","email":"grace@example.com"}'
# HTTP/1.1 201 Created
# location: /api/v1/users/0de225b5-f883-4c66-bfae-9d28f03cdcf1
# {"id":"0de225b5-f883-4c66-bfae-9d28f03cdcf1","name":"Grace","email":"grace@example.com"}
curl localhost:3000/api/v1/users/0de225b5-f883-4c66-bfae-9d28f03cdcf1 # use the id you got
# {"id":"0de225b5-f883-4c66-bfae-9d28f03cdcf1","name":"Grace","email":"grace@example.com"}
curl "localhost:3000/api/v1/users?limit=1"
# [{"id":"0de225b5-f883-4c66-bfae-9d28f03cdcf1","name":"Grace","email":"grace@example.com"}]
curl localhost:3000/api/v1/users/nope
# {"error":"User not found"}
The users live in an array in memory, so they disappear every time the server restarts, and in watch mode that means every time you save a file. That's fine for now: the database arrives in chapter 13. Notice where the array is declared: inside the plugin function, not at the top of the file. A variable at module level would be a global shared by every app instance created in the process, and two tests building two apps would see each other's users. State that belongs to an app lives inside the function that builds it. We'll follow this rule for the whole series.
Three things to keep in mind:
-
request.paramsholds the:somethingsegments of the URL,request.querythe part after?, andrequest.bodythe parsed JSON payload. - Without a schema every param and query string value is a string:
?limit=1arrives as'1', not1, which is why the code callsNumber(limit). Once we add schemas in chapter 7, Fastify converts it for you. - Those
ascasts are a temporary crutch: they tell TypeScript what to expect but check nothing at runtime. The next two chapters replace them with generics and then with schemas.
Reply: status code, headers, streaming
The POST handler already uses the two reply methods you'll need most: reply.code(201) sets the status code and reply.header() adds a response header. After that it simply returns the user, and Fastify serializes and sends it. The 404 branch works the same way: set the code, return the payload. (We'll replace that hand-made error with proper error handling in chapter 10.)
Returning a value is the normal way to answer. When you need reply.send() instead, for example to send a stream, return the reply so Fastify knows the response is being handled:
import { createReadStream } from 'node:fs';
fastify.get('/download', async (request, reply) => {
reply.type('application/json');
return reply.send(createReadStream('./package.json'));
});
Your first schema
Our POST route trusts whatever it receives. Send it a user without an email:
curl -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace"}'
# {"id":"5c1f0c0e-6d3c-4f0e-9a51-0c4b1f0a9d2e","name":"Grace"}
It answers 201 and stores a user with no email: the as cast promised TypeScript an email that was never there. The fix is a schema that describes what the body must look like. Create src/users/users.schema.ts:
// src/users/users.schema.ts
export const createUserSchema = {
body: {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
},
required: ['name', 'email'],
},
} as const;
Then use it in users.route.ts. Add the import:
import { createUserSchema } from './users.schema.ts';
and pass the schema as the second argument of the POST route:
fastify.post('/', { schema: createUserSchema }, async (request, reply) => {
Now the same request is rejected before the handler runs:
curl -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace"}'
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"body must have required property 'email'"}
curl -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace","email":"nope"}'
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"body/email must match format \"email\""}
This is plain JSON Schema written by hand. In chapter 7 we'll write the same thing with TypeBox, which also gives us the TypeScript types for free and lets us delete the as casts.
Organizing code by module
Each module starts as two files (users.service.ts and users.repository.ts join them in chapter 13, once there is business logic and a database). users.schema.ts describes the data; users.route.ts default-exports a plugin that declares the routes and their handlers. Keeping the handler next to its route definition means you read the URL, the schema, the hooks and the logic in one place, and (from chapter 7 on) the handler's types are inferred from the schema with nothing to annotate by hand.
Naming files <module>.route.ts and <module>.schema.ts (instead of a generic index.ts / schemas.ts in every folder) pays off as soon as a project has more than a couple of modules: your editor's fuzzy-finder can jump straight to users.route.ts, users.service.ts or orders.schema.ts without you needing to know which folder it lives in, and two files with the same generic name never collide when several are open as tabs at once.
Registering routes automatically
We registered the module by hand with app.register(userRoutes, { prefix: '/api/v1/users' }). For larger projects, @fastify/autoload can find and register every route file for you:
import autoload from '@fastify/autoload';
app.register(autoload, {
dir: import.meta.dirname,
matchFilter: /\.route\.(ts|js)$/, // only *.route files are plugins
options: { prefix: '/api' },
});
Autoload treats every file it finds as a plugin and uses the folder name as the URL prefix (src/users/ becomes /api/users). Because our modules sit directly under src/, it scans the whole source tree, and the matchFilter restricts it to the *.route.ts files.
In this series we'll keep registering plugins explicitly: it's more verbose, but you always see the registration order, which matters once plugins depend on each other.
⬅️ Previous chapter: Your first server (app.ts, server.ts, config.ts) · ➡️ Next chapter: TypeScript generics in routes
This article is part of the "Fastify with TypeScript" series — chapter 5 of 18.
Top comments (0)