$npx -y skills add jgamaraalv/ts-dev-kit --skill fastify-best-practicesFastify 5 best practices, API reference, and patterns for routes, plugins, hooks, validation, error handling, and TypeScript. Use when: (1) writing new Fastify routes, plugins, or hooks, (2) looking up Fastify API signatures or options, (3) debugging Fastify issues (lifecycle, en
| 1 | # Fastify 5 Best Practices |
| 2 | |
| 3 | ## Table of Contents |
| 4 | |
| 5 | - [Request lifecycle](#request-lifecycle-exact-order) |
| 6 | - [Top anti-patterns](#top-anti-patterns) |
| 7 | - [Quick patterns](#quick-patterns) |
| 8 | - [Reference files](#reference-files) |
| 9 | |
| 10 | <quick_reference> |
| 11 | |
| 12 | ## Request lifecycle (exact order) |
| 13 | |
| 14 | ``` |
| 15 | Incoming Request |
| 16 | └─ Routing |
| 17 | └─ onRequest hooks |
| 18 | └─ preParsing hooks |
| 19 | └─ Content-Type Parsing |
| 20 | └─ preValidation hooks |
| 21 | └─ Schema Validation (→ 400 on failure) |
| 22 | └─ preHandler hooks |
| 23 | └─ Route Handler |
| 24 | └─ preSerialization hooks |
| 25 | └─ onSend hooks |
| 26 | └─ Response Sent |
| 27 | └─ onResponse hooks |
| 28 | ``` |
| 29 | |
| 30 | Error at any stage → `onError` hooks → error handler → `onSend` → response → `onResponse`. |
| 31 | |
| 32 | </quick_reference> |
| 33 | |
| 34 | <anti_patterns> |
| 35 | |
| 36 | ## Top anti-patterns |
| 37 | |
| 38 | 1. **Mixing async/callback in handlers** — Use `async` OR callbacks, never both. With async, `return` the value; don't call `reply.send()` AND return. |
| 39 | |
| 40 | 2. **Returning `undefined` from async handler** — Fastify treats this as "no response yet". Return the data or call `reply.send()`. |
| 41 | |
| 42 | 3. **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`. |
| 43 | |
| 44 | 4. **Forgetting `fastify-plugin` wrapper** — Without it, decorators/hooks stay scoped to the child context. Parent and sibling plugins won't see them. |
| 45 | |
| 46 | 5. **Decorating with reference types directly** — `decorateRequest('data', {})` shares the SAME object across all requests. Use `null` initial + `onRequest` hook to assign per-request. |
| 47 | |
| 48 | 6. **Sending response in `onError` hook** — `onError` is read-only for logging. Use `setErrorHandler()` to modify error responses. |
| 49 | |
| 50 | 7. **Not handling `reply.send()` in async hooks** — Call `return reply` after `reply.send()` in async hooks to prevent "Reply already sent" errors. |
| 51 | |
| 52 | 8. **Ignoring encapsulation** — Decorators/hooks registered in child plugins are invisible to parents. Design your plugin tree carefully. |
| 53 | |
| 54 | 9. **String concatenation in SQL from route params** — Always use parameterized queries. Fastify validates input shape, not content safety. |
| 55 | |
| 56 | 10. **Missing response schema** — Without `response` schema, Fastify serializes with `JSON.stringify()` (slow) and may leak sensitive fields. Use `fast-json-stringify` via response schemas. |
| 57 | |
| 58 | </anti_patterns> |
| 59 | |
| 60 | <examples> |
| 61 | |
| 62 | ## Quick patterns |
| 63 | |
| 64 | ### Plugin with fastify-plugin (FastifyPluginCallback) |
| 65 | |
| 66 | Project convention: use `FastifyPluginCallback` + `done()` (avoids `require-await` lint errors). |
| 67 | |
| 68 | ```ts |
| 69 | import fp from "fastify-plugin"; |
| 70 | import type { FastifyPluginCallback } from "fastify"; |
| 71 | |
| 72 | const myPlugin: FastifyPluginCallback = (fastify, opts, done) => { |
| 73 | fastify.decorate("myService", new MyService()); |
| 74 | done(); |
| 75 | }; |
| 76 | |
| 77 | export default fp(myPlugin, { name: "my-plugin" }); |
| 78 | ``` |
| 79 | |
| 80 | ### Route with validation |
| 81 | |
| 82 | ```ts |
| 83 | fastify.post<{ Body: CreateUserBody }>("/users", { |
| 84 | schema: { |
| 85 | body: { |
| 86 | type: "object", |
| 87 | required: ["email", "name"], |
| 88 | properties: { |
| 89 | email: { type: "string", format: "email" }, |
| 90 | name: { type: "string", minLength: 1 }, |
| 91 | }, |
| 92 | }, |
| 93 | response: { |
| 94 | 201: { |
| 95 | type: "object", |
| 96 | properties: { |
| 97 | id: { type: "string" }, |
| 98 | email: { type: "string" }, |
| 99 | }, |
| 100 | }, |
| 101 | }, |
| 102 | }, |
| 103 | handler: async (request, reply) => { |
| 104 | const user = await createUser(request.body); |
| 105 | return reply.code(201).send(user); |
| 106 | }, |
| 107 | }); |
| 108 | ``` |
| 109 | |
| 110 | ### Hook (application-level) |
| 111 | |
| 112 | ```ts |
| 113 | fastify.addHook("onRequest", async (request, reply) => { |
| 114 | request.startTime = Date.now(); |
| 115 | }); |
| 116 | |
| 117 | fastify.addHook("onResponse", async (request, reply) => { |
| 118 | request.log.info({ elapsed: Date.now() - request.startTime }, "request completed"); |
| 119 | }); |
| 120 | ``` |
| 121 | |
| 122 | ### Error handler |
| 123 | |
| 124 | ```ts |
| 125 | fastify.setErrorHandler((error, request, reply) => { |
| 126 | request.log.error(error); |
| 127 | const statusCode = error.statusCode ?? 500; |
| 128 | reply.code(statusCode).send({ |
| 129 | error: statusCode >= 500 ? "Internal Server Error" : error.message, |
| 130 | }); |
| 131 | }); |
| 132 | ``` |
| 133 | |
| 134 | </examples> |
| 135 | |
| 136 | <references> |
| 137 | |
| 138 | ## Reference files |
| 139 | |
| 140 | Load the relevant file when you need detailed API information: |
| 141 | |
| 142 | - **Server factory & options** — constructor options, server methods, properties: [references/server-and-options.md](references/server |