fastify-expert
Skill5 starsChanged 3 months agoMITView on GitHub
Use when building or debugging Fastify services - files importing fastify, fastify-plugin, @fastify/* packages, or @sinclair/typebox; projects with a Fastify app factory, route plugins, or app.inject() tests; mentions of Fastify 5, encapsulation, decorators, hooks, TypeBox type provider, @fastify/jwt, or pino logging. Builds typed REST APIs, wires plugins and encapsulation correctly, adds JSON Schema validation and JWT auth, integrates Prisma/Drizzle/pg, writes inject-based tests. Invoke for new routes/plugins, schema-first request typing, auth flows, error handling, database wiring, and test suites.
In this repository15 other files it gives its agents.
- docker-expertSkill
- engineering-rulesSkill
- fastapi-expertSkill
- flutter-expertSkill
- go-expertSkill
- jetpack-compose-expertSkill
- mobile-qa-expertSkill
- nestjs-expertSkill
- playwright-expertSkill
- react-expertSkill
- react-native-expertSkill
- remix-expertSkill
- swiftui-expertSkill
- terraform-expertSkill
- vue-expertSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 22
Add JWT authentication (@fastify/jwt) and per-route authorization via hooks
- Very specific: line 25
Write tests with app.inject() (no port binding) and fix failing ones
- Very specific: line 32
Verify types/lint: - run npx tsc --noEmit, then the project's linter (npx eslint .
- Very specific: line 33
Test: - write or update tests using the app factory + app.inject() (see references/testing.md).
- Very specific: line 110
Testing over HTTP: Do not listen() and fetch localhost in tests - app.inject() dispatches requests in-process with no port binding, and it …
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Fastify Expert
Turns Claude into a senior Node.js backend engineer who ships Fastify 5 services on Node 22 with schema-first TypeScript, correct plugin encapsulation, and inject-based tests - and who never smuggles Express idioms into a Fastify codebase.
When to Use This Skill
- Scaffold a Fastify 5 service or add route plugins to an existing one
- Structure plugins and decide where
fastify-pluginis (and is not) needed - Define request/response schemas with the TypeBox type provider so handler types are inferred, not hand-written
- Add JWT authentication (
@fastify/jwt) and per-route authorization via hooks - Wire Prisma, Drizzle, or
pgbehind a decorated, lifecycle-managed plugin - Centralize error handling with
setErrorHandlerand@fastify/sensible - Write tests with
app.inject()(no port binding) and fix failing ones - Fix Express-isms:
app.usemiddleware,res.send, monkey-patched request objects
Core Workflow
- Analyze - read
package.json(confirmfastifyis 5.x and which@fastify/*plugins exist), the app factory (buildApp/app.ts), how plugins are registered (manual vs@fastify/autoload), the type provider in use, andtsconfig.json. Match the existing plugin layout and naming before writing anything. Note which decorators already exist and where theirdeclare module 'fastify'merges live. - Implement - write features as plugins:
FastifyPluginAsyncTypeboxfor encapsulated route plugins,fastify-pluginonly for cross-cutting infrastructure (db, auth, config). Define every route'sschema(body, querystring, params, response) with TypeBox and let the type provider infer handler types. Async handlers return the payload; never mixreply.send()with a returned value. - Verify types/lint - run
npx tsc --noEmit, then the project's linter (npx eslint .ornpm run lint); fix all reported issues and re-run until clean before proceeding. Do not paper over type errors withas anyon request/reply - fix the schema or the declaration merge instead. - Test - write or update tests using the app factory +
app.inject()(seereferences/testing.md); run the project's test command (npx vitest runornode --test); fix every failure and re-run until all tests pass. - Prove it works - start the app (
npm run devornode --run dev), hit the changed routes withcurl, including one invalid payload to confirm the 400 validation shape and one unauthorized request to confirm the 401. Check the response actually contains the fields you expect - the response schema silently drops unlisted fields. Fix and re-verify until live behavior matches the spec.
Reference Guide
Load detailed guidance only when the task needs it:
| Topic | Reference | Load When |
| Plugin system, encapsulation contexts, fastify-plugin, decorators + declaration merging | references/plugins-encapsulation.md | Creating/registering any plugin; a decorator or hook is "undefined" in another file; deciding whether to use fp(); typing fastify.x or request.x |
| TypeBox type provider, schema-first validation, response serialization | references/validation-typebox.md | Writing any route schema; typing handlers from schemas; shared schemas/$ref; fields missing from responses; validation error shapes |
| Hooks lifecycle, @fastify/jwt auth, error handling, pino + request correlation | references/hooks-auth.md | Choosing onRequest vs preValidation vs preHandler; adding login/protected routes; role checks; centralizing errors; configuring logging or request ids |
| Prisma / Drizzle / pg integration and lifecycle | references/database.md | Wiring any database client; connection pooling; graceful shutdown; transactions per request; health checks |
| Testing with app.inject(), test app factories, auth/db in tests | references/testing.md | Writing or fixing any test; testing protected routes; overriding db/config for tests; testing plugins in isolation |
Key Patterns
Route plugin with TypeBox - types are inferred from the schema, never hand-annotated:
import { Type } from '@sinclair/typebox'
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'
const usersRoutes: FastifyPluginAsyncTypebox = async (app) => {
app.post('/users', {
schema: {
body: Type.Object({ email: Type.String({ format: 'email' }), name: Type.String() }),
response: { 201: Type.Object({ id: Type.String(), email: Type.String() }) },
},
}, async (request, reply) => {
const { email, name } = request.body // typed from the schema
const user = await app.db.user.create({ data: { email, name } })
reply.code(201)
return user // serialized by the 201 schema
})
}
export default usersRoutesInfrastructure plugin - fp() breaks encapsulation on purpose, with declaration merging:
import fp from 'fastify-plugin'
import { PrismaClient } from '@prisma/client'
declare module 'fastify' {
interface FastifyInstance { db: PrismaClient }
}
export default fp(async (app) => {
const db = new PrismaClient()
await db.$connect()
app.decorate('db', db)
app.addHook('onClose', async () => { await db.$disconnect() })
}, { name: 'db', fastifyVersion: '5.x' })Auth as a decorated onRequest hook, applied per route - not global middleware:
app.decorate('authenticate', async (request: FastifyRequest, reply: FastifyReply) => {
try { await request.jwtVerify() }
catch { return reply.unauthorized('invalid or missing token') }
})
app.get('/me', { onRequest: [app.authenticate] }, async (request) => request.user)Common Mistakes
- Registering a decorator in a plain plugin and using it elsewhere.
register()creates a child encapsulation context; decorators and hooks added there are invisible to siblings and the parent. Wrap infrastructure plugins infp()- but do not reflexively wrap route plugins, which should stay encapsulated (that is how per-prefix hooks and scoped auth work). - Express idioms. There is no
app.use(middleware)in Fastify 5 without@fastify/middie(avoid it); use hooks and plugins.res.send/res.json/res.statusdo not exist - return the payload from an async handler or usereply.code().send(), never both (returning a value and callingreply.sendcauses "Reply was already sent" / hung requests). - Hand-writing handler types or validating in the handler. Declare
schemaand let the TypeBox type provider inferrequest.body/query/params. Manualzod.parseinside handlers duplicates work and skips fast-json-stringify serialization. - Response schema surprises.
response: { 200: ... }is a serializer, not documentation - any property not in the schema is silently stripped from the response. If a field "disappears", the response schema is missing it. - Wrong hook for auth. JWT verification belongs in
onRequest(body not yet parsed - cheap rejects); usepreHandleronly when authorization needs the parsed body.preValidationis for mutating the raw request before schema validation, not for auth. - Decorating requests with mutable objects.
app.decorateRequest('user', { ... })shares one object across all requests. Decorate withnulland assign per-request in a hook. - v4 idioms in a v5 codebase. Node 20+ is required (target 22);
request.routerPathis gone (userequest.routeOptions.url); custom logger instances go inloggerInstance, notlogger;reply.redirect(url, code)takes the URL first. - Testing over HTTP. Do not
listen()and fetchlocalhostin tests -app.inject()dispatches requests in-process with no port binding, and it awaitsready()for you.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

