| name | fastify |
| description | Fastify plugins, hooks, validation, serialization, and performance optimization patterns. |
| allowed-tools | Read, Write, Edit, Bash, Glob, Grep |
| graph | {"domains":["domain:web-development"],"specializations":["specialization:web-development"],"skillAreas":["skill-area:backend-api-design","skill-area:middleware-design"],"roles":["role:backend-engineer"],"topics":["topic:rest","topic:api-design"]} |
Fastify Skill
Expert assistance for building high-performance APIs with Fastify.
Capabilities
- Configure Fastify with plugins
- Implement hooks for lifecycle management
- Set up JSON Schema validation
- Optimize serialization for performance
- Build type-safe APIs with TypeScript
- Create reusable plugins
Usage
Invoke this skill when you need to:
- Build high-performance APIs
- Implement schema validation
- Create custom plugins
- Optimize JSON serialization
- TypeScript integration
Inputs
| Parameter | Type | Required | Description |
|---|
| routePrefix | string | Yes | Route prefix |
| validation | boolean | No | Add JSON Schema validation |
| plugins | array | No | Plugins to use |
Patterns
Application Setup
import Fastify, { FastifyInstance } from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';
import { usersRoutes } from './routes/users';
import { authRoutes } from './routes/auth';
import { errorHandler } from './plugins/error-handler';
export async function buildApp(): Promise<FastifyInstance> {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty' }
: undefined,
},
ajv: {
: {
: ,
: ,
: ,
},
},
});
app.(helmet);
app.(cors, {
: process.. || ,
: ,
});
app.(rateLimit, {
: ,
: ,
});
app.(swagger, {
: {
: {
: ,
: ,
},
: {
: {
: {
: ,
: ,
},
},
},
},
});
app.(swaggerUi, {
: ,
});
app.(errorHandler);
app.(authRoutes, { : });
app.(usersRoutes, { : });
app.(, () => ({
: ,
: ().(),
}));
app;
}
Routes with Schema Validation
import { FastifyPluginAsync } from 'fastify';
import { Type, Static } from '@sinclair/typebox';
import { UsersService } from '../services/users.service';
const UserSchema = Type.Object({
id: Type.String(),
name: Type.String(),
email: Type.String({ format: 'email' }),
role: Type.Union([Type.Literal('user'), Type.Literal('admin')]),
createdAt: Type.String({ format: 'date-time' }),
});
const CreateUserSchema = Type.Object({
name: Type.String({ minLength: 1 }),
email: .({ : }),
: .({ : }),
: .(.([.(), .()])),
});
= .();
= .({
: .(.({ : , : })),
: .(.({ : , : , : })),
: .(.()),
});
= < >;
= < >;
= < >;
= < >;
: = (fastify) => {
service = ();
fastify.<{ : }>(, {
: {
: [],
: ,
: {
: .({
: .(),
: .({
: .(),
: .(),
: .(),
}),
}),
},
},
: [fastify.],
}, (request) => {
service.(request.);
});
fastify.<{ : { : } }>(, {
: {
: [],
: .({ : .() }),
: { : },
},
: [fastify.],
}, (request, reply) => {
user = service.(request..);
(!user) {
reply.().({ : });
}
user;
});
fastify.<{ : }>(, {
: {
: [],
: ,
: { : },
},
: [fastify., fastify.([])],
}, (request, reply) => {
user = service.(request.);
reply.().(user);
});
fastify.<{ : { : }; : }>(, {
: {
: [],
: .({ : .() }),
: ,
: { : },
},
: [fastify.],
}, (request) => {
service.(request.., request.);
});
fastify.<{ : { : } }>(, {
: {
: [],
: .({ : .() }),
},
: [fastify., fastify.([])],
}, (request, reply) => {
service.(request..);
reply.().();
});
};
Hooks and Plugins
import { FastifyPluginAsync, FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';
import jwt from '@fastify/jwt';
declare module 'fastify' {
interface FastifyInstance {
authenticate: (request: FastifyRequest) => Promise<void>;
authorize: (roles: string[]) => (request: FastifyRequest) => Promise<void>;
}
}
declare module '@fastify/jwt' {
interface FastifyJWT {
payload: { id: string; email: string; role: string };
user: { id: string; email: string; role: string };
}
}
const : = (fastify) => {
fastify.(jwt, {
: process..!,
});
fastify.(, (: ) => {
request.();
});
fastify.(, {
(: ) => {
request.();
(!roles.(request..)) {
fastify..();
}
};
});
};
(authPlugin, {
: ,
});
{ } ;
fp ;
: = (fastify) => {
fastify.( {
fastify..(error);
(error.) {
reply.().({
: ,
: error.,
});
}
statusCode = error. || ;
message = statusCode === && process.. ===
?
: error.;
reply.(statusCode).({ : message });
});
};
(errorHandler, {
: ,
});
Custom Hooks
fastify.addHook('onRequest', async (request, reply) => {
request.startTime = Date.now();
});
fastify.addHook('onResponse', async (request, reply) => {
const duration = Date.now() - request.startTime;
request.log.info({ duration }, 'Request completed');
});
fastify.addHook('onSend', async (request, reply, payload) => {
return payload;
});
Best Practices
- Use JSON Schema for validation
- Leverage TypeBox for TypeScript schemas
- Create reusable plugins with fastify-plugin
- Use hooks for cross-cutting concerns
- Enable schema serialization for performance
Target Processes
- high-performance-api
- nodejs-microservices
- api-development
- backend-optimization