Skip to main content
skill CX Codex

fastify-typescript — Claude Code skill: Fastify API conventions

Gives the agent a rulebook for Fastify and TypeScript: validation schemas, plugins, Prisma access and Jest tests. Useful when you build a typed REST API.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add Mindrally/skills --skill fastify-typescript -a claude-code
Open on GitHub

What fastify-typescript does

The skill hands your agent a set of coding rules. Declare types for variables and functions, skip any, use const objects instead of enums, prefer interfaces for object shapes, and pull in types with import type. Naming is covered too: PascalCase for types, camelCase for functions, kebab-case for files, UPPERCASE for environment variables.

Project layout follows the same idea — src/routes/{resource}/ holding index.ts, handlers.ts and schemas.ts, plus separate folders for plugins, services, repositories, types and config. Validation runs on JSON Schema with @sinclair/typebox, shared pieces become plugins registered through fastify-plugin, and database work goes through Prisma repositories with transactions. Errors get a custom class carrying statusCode and a global setErrorHandler; tests use Jest and app.inject().

The rules assume Prisma is your ORM. The database plugin and repository examples are built around PrismaClient, so a different data layer means rewriting those parts. Security guidance names @fastify/helmet, @fastify/rate-limit, @fastify/cors and JWT via @fastify/jwt — worth checking whether your project already wires them up.

What it helps with

  • split Fastify routes into per-resource folders
  • define request and response schemas with TypeBox
  • register Prisma as a plugin with an onClose hook
  • return consistent error payloads from one handler
  • cover a route with an integration test using app.inject()

Example prompts for the agent

  • add an orders resource following the skill's folder layout
  • rewrite this route with TypeBox schemas instead of manual body checks
  • move Prisma into a plugin with a decorator and disconnect on onClose

How to install fastify-typescript

1Skills CLI (Vercel)

npx skills add Mindrally/skills --skill fastify-typescript -a claude-code

2Manually: put the files in place

~/.claude/skills/fastify-typescript/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/fastify-typescript/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about fastify-typescript

How do I install fastify-typescript in Claude?

Run npx skills add Mindrally/skills --skill fastify-typescript -a claude-code. The skill then lives at ~/.claude/skills/fastify-typescript/SKILL.md.

What does fastify-typescript do?

It gives the agent conventions for building Fastify APIs in TypeScript: typing, naming, folder structure, validation schemas, plugins, Prisma access and Jest tests.

Does fastify-typescript require Prisma?

The data-access examples rely on PrismaClient and repository classes. With a different database layer you will need to adapt those snippets.

Source text

SKILL.md · Apache-2.0
---
name: fastify-typescript
description: Guidelines for building high-performance APIs with Fastify and TypeScript, covering validation, Prisma integration, and testing best practices
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# Fastify TypeScript Development

You are an expert in Fastify and TypeScript development with deep knowledge of building high-performance, type-safe APIs.

## TypeScript General Guidelines

### Basic Principles

- Use English for all code and documentation
- Always declare types for variables and functions (parameters and return values)
- Avoid using `any` type - create necessary types instead
- Use JSDoc to document public classes and methods
- Write concise, maintainable, and technically accurate code
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization to adhere to DRY principles

### Nomenclature

- Use PascalCase for types and interfaces
- Use camelCase for variables, functions, and methods
- Use kebab-case for file and directory names
- Use UPPERCASE for environment variables
- Use descriptive variable names with auxiliary verbs: `isLoading`, `hasError`, `canDelete`
- Start each function with a verb

### Functions

- Write short functions with a single purpose
- Use arrow functions for simple operations
- Use async/await consistently throughout the codebase
- Use the RO-RO pattern (Receive an Object, Return an Object) for multiple parameters

### Types and Interfaces

- Prefer interfaces over types for object shapes
- Avoid enums; use maps or const objects instead
- Use Zod for runtime validation with inferred types
- Use `readonly` for immutable properties
- Use `import type` for type-only imports

## Fastify-Specific Guidelines

### Project Structure

```
src/
  routes/
    {resource}/
      index.ts
      handlers.ts
      schemas.ts
  plugins/
    auth.ts
    database.ts
    cors.ts
  services/
    {domain}Service.ts
  repositories/
    {entity}Repository.ts
  types/
    index.ts
  utils/
  config/
  app.ts
  server.ts
```

### Route Organization

- Organize routes by resource/domain
- Use route plugins for modular registration
- Define schemas alongside route handlers
- Use route prefixes for API versioning

```typescript
import { FastifyPluginAsync } from 'fastify';

const usersRoutes: FastifyPluginAsync = async (fastify) => {
  fastify.get('/', { schema: listUsersSchema }, listUsersHandler);
  fastify.get('/:id', { schema: getUserSchema }, getUserHandler);
  fastify.post('/', { schema: createUserSchema }, createUserHandler);
  fastify.put('/:id', { schema: updateUserSchema }, updateUserHandler);
  fastify.delete('/:id', { schema: deleteUserSchema }, deleteUserHandler);
};

export default usersRoutes;
```

### Schema Validation with JSON Schema / Ajv

- Define JSON schemas for all request/response validation
- Use @sinclair/typebox for type-safe schema definitions
- Leverage Fastify's built-in Ajv integration

```typescript
import { Type, Static } from '@sinclair/typebox';

const UserSchema = Type.Object({
  id: Type.String({ format: 'uuid' }),
  name: Type.String({ minLength: 1 }),
  email: Type.String({ format: 'email' }),
  createdAt: Type.String({ format: 'date-time' }),
});

type User = Static<typeof UserSchema>;

const createUserSchema = {
  body: Type.Object({
    name: Type.String({ minLength: 1 }),
    email: Type.String({ format: 'email' }),
  }),
  response: {
    201: UserSchema,
    400: ErrorSchema,
  },
};
```

### Plugins and Decorators

- Use plugins for shared functionality
- Decorate Fastify instance with services and utilities
- Register plugins with proper encapsulation

```typescript
import fp from 'fastify-plugin';

const databasePlugin = fp(async (fastify) => {
  const prisma = new PrismaClient();

  await prisma.$connect();

  fastify.decorate('prisma', prisma);

  fastify.addHook('onClose', async () => {
    await prisma.$disconnect();
  });
});

export default databasePlugin;
```

### Prisma Integration

- Use Prisma as the ORM for database operations
- Create repository classes for data access
- Use transactions for complex operations

```typescript
class UserRepository {
  constructor(private prisma: PrismaClient) {}

  async findById(id: string): Promise<User | null> {
    return this.prisma.user.findUnique({ where: { id } });
  }

  async create(data: CreateUserInput): Promise<User> {
    return this.prisma.user.create({ data });
  }
}
```

### Error Handling

- Use Fastify's built-in error handling
- Create custom error classes for domain errors
- Return consistent error responses

```typescript
import { FastifyError } from 'fastify';

class NotFoundError extends Error implements FastifyError {
  code = 'NOT_FOUND';
  statusCode = 404;

  constructor(resource: string, id: string) {
    super(`${resource} with id ${id} not found`);
    this.name = 'NotFoundError';
  }
}

// Global error handler
fastify.setErrorHandler((error, request, reply) => {
  const statusCode = error.statusCode || 500;

  reply.status(statusCode).send({
    error: error.name,
    message: error.message,
    statusCode,
  });
});
```

### Testing with Jest

- Write unit tests for services and handlers
- Use integration tests for routes
- Mock external dependencies

```typescript
import { build } from '../app';

describe('Users API', () => {
  let app: FastifyInstance;

  beforeAll(async () => {
    app = await build();
  });

  afterAll(async () => {
    await app.close();
  });

  it('should list users', async () => {
    const response = await app.inject({
      method: 'GET',
      url: '/api/users',
    });

    expect(response.statusCode).toBe(200);
    expect(JSON.parse(response.payload)).toBeInstanceOf(Array);
  });
});
```

### Performance

- Fastify is one of the fastest Node.js frameworks
- Use schema validation for automatic serialization optimization
- Enable logging only when needed in production
- Use connection pooling for database connections

### Security

- Use @fastify/helmet for security headers
- Implement rate limiting with @fastify/rate-limit
- Use @fastify/cors for CORS configuration
- Validate all inputs with JSON Schema
- Use JWT for authentication with @fastify/jwt

© Mindrally · Apache-2.0 · Mindrally/skills

Similar skills

All skills for Backend and APIs →

From the same set214

openai-api-development A skill that steers your coding agent through Anthropic API work: Claude calls, function calling, embeddings and Assistants API, with Python examples. CX Codex +1 864installs jest A skill that tells your agent how to write Jest tests: structure, mocks, assertions, async. Useful when AI writes the tests in your repo. CX Codex +1 864installs ruby-rails This skill hands your agent Rails conventions: generators over boilerplate, ActiveRecord patterns, Hotwire, background jobs and tests. Useful on a fresh app or an existing one. CX Codex +1 862installs seo-best-practices Provides search optimization guidelines for web apps. Helps configure metadata, JSON-LD schemas, rendering modes, and Core Web Vitals. CX Codex +1 858installs deep-learning-python Enforces deep learning standards across PyTorch, Transformers, Diffusers, and Gradio. Guides your AI agent to produce clean ML code with mixed precision and LoRA fine-tuning. CX Codex +1 849installs performance-optimization A rule set for web performance: server-side rendering, CSS, JavaScript, assets and caching. Useful when your agent writes frontend code and you want a bar to hold it to. CX Codex +1 848installs sass-best-practices A skill that hands your agent a rulebook for indented-syntax Sass: file layout, variables, mixins, BEM. Useful when the project stylesheets are .sass, not SCSS. CX Codex +1 845installs nextjs-react-redux-typescript-cursor-rules Development guidelines for Next.js, React, Redux Toolkit, and TypeScript. Enforces Server Component defaults, strict typing, and specific code style standards. CX Codex +1 842installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor