Skip to content
Development
Skill

/api-framework-fastify

Fastify routes, JSON Schema validation, plugin system, TypeScript type providers

From plugin
skills
26200 skills

Claude Code

$ npx -y skills add agents-inc/skills --skill api-framework-fastify --agent claude-code

SKILL.md

api-framework-fastify.SKILL.md
name: api-framework-fastify
description: Fastify routes, JSON Schema validation, plugin system, TypeScript type providers

API Development with Fastify

> **Quick Guide:** Use Fastify for high-performance Node.js REST APIs with built-in JSON Schema validation and powerful plugin encapsulation. Use `@fastify/type-provider-typebox` for end-to-end type safety (both `Type` and `TypeBoxTypeProvider` re-exported from it). Wrap shared plugins with `fastify-plugin` to expose decorators. Always define response schemas for serialization performance and data leak prevention.

---

<critical_requirements>

CRITICAL: Before Using This Skill

**(You MUST use `withTypeProvider<>()` for type-safe request/response handling)**

**(You MUST wrap shared plugins with `fastify-plugin` to expose decorators to parent scope)**

**(You MUST define response schemas to enable fast-json-stringify optimization)**

**(You MUST use named constants for HTTP status codes - never raw numbers)**

</critical_requirements>

---

**Auto-detection:** Fastify, fastify.register, fastify.decorate, fastify-plugin, TypeBox, @fastify/type-provider-typebox, @fastify/type-provider-json-schema-to-ts, fastify-type-provider-zod, preHandler, onRequest, preSerialization, JSON Schema validation, fast-json-stringify, FastifyPluginAsyncTypebox

**When to use:**

  • Building high-performance REST APIs (45k+ req/sec benchmarks)
  • Need schema-based validation with automatic coercion
  • Want plugin encapsulation for modular architecture
  • Require lifecycle hooks for cross-cutting concerns
  • Building APIs with strict TypeScript type safety requirements

**When NOT to use:**

  • Simple internal APIs without performance requirements (consider your existing solution)
  • GraphQL APIs (use dedicated GraphQL servers)
  • Edge/serverless with size constraints (Fastify has larger footprint than minimal frameworks)
  • When middleware ecosystem compatibility with Express is required

**Key patterns covered:**

  • Server setup with TypeScript type providers
  • Plugin system and encapsulation patterns
  • JSON Schema validation for request/response
  • Lifecycle hooks (onRequest, preHandler, onSend, etc.)
  • Decorators for extending Fastify/Request/Reply
  • Error handling with setErrorHandler
  • Route organization with prefix patterns

---

**Detailed Resources:**

  • [examples/core.md](examples/core.md) - Server setup, routes, schemas, error handling, testing
  • [examples/plugins.md](examples/plugins.md) - Plugin system, encapsulation, decorators
  • [examples/schemas.md](examples/schemas.md) - TypeBox schemas, validation, type-safe routes
  • [examples/hooks.md](examples/hooks.md) - Lifecycle hooks and cross-cutting concerns
  • [reference.md](reference.md) - Decision frameworks, anti-patterns, quick reference

---

<philosophy>

Philosophy

**Schema-first, compiled validation.** Fastify compiles JSON schemas at startup into highly optimized validator functions. This provides both runtime safety and documentation from a single source of truth.

**Plugin encapsulation creates microservices in a monolith.** Each plugin has its own scope for decorators and hooks. Child plugins inherit from parents, but parents cannot access child resources - enabling clean separation of concerns.

**Performance without sacrifice.** Fastify achieves 2-3x throughput over Express while maintaining developer ergonomics through TypeScript integration and comprehensive hook system.

</philosophy>

---

<patterns>

Core Patterns

Pattern 1: Server Setup with Type Provider

Configure Fastify with TypeBox for compile-time AND runtime type safety. `Type` is re-exported from `@fastify/type-provider-typebox`.

import Fastify from "fastify";
import { Type, TypeBoxTypeProvider } from "@fastify/type-provider-typebox";

const SERVER_PORT = 3000;
const SERVER_HOST = "0.0.0.0";

const buildServer = () => {
  const server = Fastify({
    logger: { level: process.env.LOG_LEVEL ?? "info" },
  }).withTypeProvider<TypeBoxTypeProvider>();

  server.setErrorHandler(errorHandler);
  server.register(userRoutes, { prefix: "/api/users" });

  return server;
};

export { buildServer };

**Why good:** TypeBox provider enables type inference from schemas, factory function enables testing, `Type` imported from same package

> Full example with startup, error handling, and testing: [examples/core.md](examples/core.md)

---

Pattern 2: Schema Definition with TypeBox

Define schemas that provide both TypeScript types AND runtime validation from a single source.

import { Type, Static } from "@fastify/type-provider-typebox";

const MIN_USERNAME_LENGTH = 3;
const MAX_USERNAME_LENGTH = 50;

export const UserSchema = Type.Object({
  id: Type.String({ format: "uuid" }),
  username: Type.String({
    minLength: MIN_USERNAME_LENGTH,
    maxLength: MAX_USERNAME_LENGTH,
  }),
  email: Type.String({ format: "email" }),
});

// Derive TypeScript types from schemas
export type User = Static<typeof UserSchema>;

**Why good:** Single source of truth for types and validation, `Static<>` derives TS types automatically

> Full schema patterns (composition, partial updates, reusable components): [examples/schemas.md](examples/schemas.md)

---

Pattern 3: Route Definition with Full Schema

Define routes with request AND response schemas for complete type safety and serialization optimization.

import type { FastifyPluginAsync } from "fastify";
import { Type } from "@fastify/type-provider-typebox";

const HTTP_OK = 200;
const HTTP_NOT_FOUND = 404;

export const userRoutes: FastifyPluginAsync = async (fastify) => {
  fastify.get(
    "/:id",
    {
      schema: {
        params: UserParamsSchema,
        response: {
          [HTTP_OK]: UserSchema,
          [HTTP_NOT_FOUND]: ErrorSchema,
        },
      },
    },
    async (request, reply) => {
      const user = await fastify.userService.findById(request.params.id);
      if (!user) {
        return reply.status(HTTP_NOT_FO
Read more
@agents-inc
Ships withskills

The official skills marketplace for Agents Inc. 230+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?

Stars on GitHub

Momentum

stars in total
26
Star history of agents-inc/skills on GitHub, a chart by star-history.com

Other skills on skills.

ai-infrastructure-litellm

ai-infrastructure-lite…

LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking,…

@agents-inc@agents-incInstall Skill
ai-infrastructure-modal

ai-infrastructure-moda…

Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client…

@agents-inc@agents-incInstall Skill
ai-infrastructure-ollama

ai-infrastructure-olla…

Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output,…

@agents-inc@agents-incInstall Skill

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills10d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc11d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react1d252k
@facebook@facebookInstall Skill

Questions about api-framework-fastify.

Which coding agents can use api-framework-fastify?
api-framework-fastify installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.