/ts-dev-kit:fastify-best-practicesfrom ts-dev-kit
Fastify 5 best practices, API reference, and patterns for routes, plugins, hooks, validation, error handling, and TypeScript. Activates when writing routes, plugins, hooks, debugging lifecycle issues, or reviewing anti-patterns.
Ships in ts-dev-kit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
<quick_reference>
Incoming Request
└─ Routing
└─ onRequest hooks
└─ preParsing hooks
└─ Content-Type Parsing
└─ preValidation hooks
└─ Schema Validation (→ 400 on failure)
└─ preHandler hooks
└─ Route Handler
└─ preSerialization hooks
└─ onSend hooks
└─ Response Sent
└─ onResponse hooks
Error at any stage → onError hooks → error handler → onSend → response → onResponse.
</quick_reference>
<anti_patterns>
Mixing async/callback in handlers — Use async OR callbacks, never both. With async, return the value; don't call reply.send() AND return.
Returning undefined from async handler — Fastify treats this as "no response yet". Return the data or call reply.send().
Using arrow functions when you need this — Arrow functions don't bind this to the Fastify instance. Use function declarations for handlers that need this.
Forgetting fastify-plugin wrapper — Without it, decorators/hooks stay scoped to the child context. Parent and sibling plugins won't see them.
Decorating with reference types directly — decorateRequest('data', {}) shares the SAME object across all requests. Use null initial + onRequest hook to assign per-request.
Sending response in onError hook — onError is read-only for logging. Use setErrorHandler() to modify error responses.
Not handling reply.send() in async hooks — Call return reply after reply.send() in async hooks to prevent "Reply already sent" errors.
Ignoring encapsulation — Decorators/hooks registered in child plugins are invisible to parents. Design your plugin tree carefully.
String concatenation in SQL from route params — Always use parameterized queries. Fastify validates input shape, not content safety.
Missing response schema — Without response schema, Fastify serializes with JSON.stringify() (slow) and may leak sensitive fields. Use fast-json-stringify via response schemas.
</anti_patterns>
Project convention: use FastifyPluginCallback + done() (avoids require-await lint errors).
import fp from "fastify-plugin";
import type { FastifyPluginCallback } from "fastify";
const myPlugin: FastifyPluginCallback = (fastify, opts, done) => {
fastify.decorate("myService", new MyService());
done();
};
export default fp(myPlugin, { name: "my-plugin" });
fastify.post<{ Body: CreateUserBody }>("/users", {
schema: {
body: {
type: "object",
required: ["email", "name"],
properties: {
email: { type: "string", format: "email" },
name: { type: "string", minLength: 1 },
},
},
response: {
201: {
type: "object",
properties: {
id: { type: "string" },
email: { type: "string" },
},
},
},
},
handler: async (request, reply) => {
const user = await createUser(request.body);
return reply.code(201).send(user);
},
});
fastify.addHook("onRequest", async (request, reply) => {
request.startTime = Date.now();
});
fastify.addHook("onResponse", async (request, reply) => {
request.log.info({ elapsed: Date.now() - request.startTime }, "request completed");
});
fastify.setErrorHandler((error, request, reply) => {
request.log.error(error);
const statusCode = error.statusCode ?? 500;
reply.code(statusCode).send({
error: statusCode >= 500 ? "Internal Server Error" : error.message,
});
});
Load the relevant file when you need detailed API information:
references/hooks-and-lifecycle.md (opens in a new tab)references/plugins-and-encapsulation.md (opens in a new tab)references/request-reply-errors.md (opens in a new tab)references/routes-and-handlers.md (opens in a new tab)references/server-and-options.md (opens in a new tab)references/typescript-and-logging.md (opens in a new tab)references/validation-and-serialization.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
22 skills in this plugin
/bullmqBullMQ queue system reference for Redis-backed job queues, workers, flows, and schedulers. Use when: (1) creating queues and workers with BullMQ, (2) adding jobs (delayed, prioritized, repeatable, deduplicated), (3) setting up FlowProducer parent-child job hierarchies, (4) configuring retry strategies, rate limiting, or concurrency, (5) implementing job schedulers with cron/interval patterns, (6) preparing BullMQ for production (graceful shutdown, Redis config, monitoring), or (7) debugging stalled jobs or connection issues/codebase-adapterAdapts ts-dev-kit plugin files to the host project where it is installed. Use when: (1) installing ts-dev-kit in a new project for the first time, (2) project tech stack or structure has changed, (3) agents reference wrong paths, unavailable skills, or missing MCPs, (4) the user says 'adapt the plugin', 'configure ts-dev-kit for this project', 'sync plugin to this codebase', or 'update plugin context'. Surgically edits specific sections in plugin skills and agent definitions — domain area tables, skill/MCP references, quality gate commands, project paths, and package names — without touching any workflow logic, execution protocols, or dispatch patterns./composition-patternsReact composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.npx claudepluginhub jgamaraalv/ts-dev-kit --plugin ts-dev-kitOther plugins' skills for the same job