Fastify Request and Reply Generics
What you'll learn: How to use Fastify's powerful generic types to make your route handlers fully type-safe for params, body, query strings, and headers.
The Problem: Generic Request and Reply Types
When you write Fastify route handlers, the default FastifyRequest and FastifyReply types don't know anything about your specific route. They treat everything as unknown or broad types, leaving you without autocomplete or type checking for the actual data your route expects.
Fastify solves this with generics — you can pass type information directly to FastifyRequest and FastifyReply to describe the exact shape of your route's data.
The RouteGeneric Interface
Fastify uses a special interface shape called RouteGeneric that has four optional properties:
interface MyRouteGeneric {
Params?: { id: string };
Body?: { name: string; email: string };
Querystring?: { sort?: string };
Headers?: { 'x-api-key': string };
}
You then pass this to FastifyRequest and FastifyReply as a type parameter.
Type-Safe Request Properties
import { FastifyRequest, FastifyReply } from 'fastify';
interface UserRouteGeneric {
Params: { userId: string };
Body: { name: string; age: number };
Querystring: { include?: 'profile' | 'settings' };
Headers: { authorization: string };
}
async function updateUser(
request: FastifyRequest<UserRouteGeneric>,
reply: FastifyReply
) {
// Fully typed access
const userId = request.params.userId; // string
const name = request.body.name; // string
const include = request.query.include; // 'profile' | 'settings' | undefined
const auth = request.headers.authorization; // string
return reply.send({ updated: true });
}
Every property now has precise types and autocomplete!
Typing Just What You Need
You don't have to specify all four properties — only include what your route actually uses:
interface GetPostGeneric {
Params: { postId: string };
Querystring: { preview?: boolean };
}
async function getPost(
request: FastifyRequest<GetPostGeneric>,
reply: FastifyReply
) {
const postId = request.params.postId; // string
const preview = request.query.preview; // boolean | undefined
// body and headers remain untyped (unknown)
}
Why This Matters
Without generics, you'd need to use type assertions everywhere or accept unsafe any types. Fastify's approach gives you compile-time guarantees that your route handler matches your route definition, catches typos, and provides full IntelliSense for all request properties.
This pattern works especially well when combined with validators — you can share the same type definition between your validation schema and your handler signature.
Key Takeaway: Fastify's FastifyRequest<RouteGeneric> and FastifyReply generics let you specify precise types for params, body, query, and headers, giving you full type safety and autocomplete in your route handlers without repetitive assertions.