fastify
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "fastify" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-afcf143b6f639b5fe8653cd186d2e04e1471ec4e4da2856f5b0b90e3724cc783. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Fastify is a high-performance Node.js web framework focused on developer experience and low overhead. Suitable for building fast APIs, it provides JSON Schema validation, a powerful plugin system, lifecycle hooks, and automatic serialization.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Fastify is one of the fastest Node.js web frameworks. It validates requests via JSON Schema, serializes responses automatically, and organizes code through an encapsulated plugin system.
- Testing
- Not tested
Browse files
Frontmatter
name: fastify
description: |
Fastify is a high-performance Node.js web framework focused on developer experience
and low overhead. It features JSON Schema validation, a powerful plugin system,
lifecycle hooks, and automatic serialization for blazing-fast APIs.
license: Apache-2.0
compatibility: 'node >= 18, npm or yarn or pnpm'
metadata:
author: terminal-skills
version: 1.0.0
category: development
tags:
- node
- javascript
- api
- rest
- performance
- pluginsFastify
Fastify is one of the fastest Node.js web frameworks. It validates requests via JSON Schema, serializes responses automatically, and organizes code through an encapsulated plugin system.
Installation
# Create Fastify project
mkdir my-api && cd my-api
npm init -y
npm i fastify @fastify/autoload @fastify/sensible @fastify/cors @fastify/jwt
Project Structure
# Recommended Fastify project layout
src/
├── app.js # App factory
├── server.js # Entry point
├── plugins/ # Shared plugins (db, auth)
│ ├── db.js
│ └── auth.js
├── routes/ # Route modules
│ ├── articles/
│ │ ├── index.js # Route handler
│ │ └── schema.js # JSON schemas
│ └── health.js
└── test/
└── articles.test.js
App Setup
// src/app.js — application factory with autoload
import Fastify from 'fastify';
import autoload from '@fastify/autoload';
import sensible from '@fastify/sensible';
import cors from '@fastify/cors';
import { join } from 'node:path';
export function buildApp(opts = {}) {
const app = Fastify({ logger: true, ...opts });
app.register(sensible);
app.register(cors, { origin: true });
app.register(autoload, { dir: join(import.meta.dirname, 'plugins') });
app.register(autoload, { dir: join(import.meta.dirname, 'routes'), options: { prefix: '/api' } });
return app;
}
// src/server.js — start the server
import { buildApp } from './app.js';
const app = buildApp();
app.listen({ port: 3000, host: '0.0.0.0' }, (err) => {
if (err) { app.log.error(err); process.exit(1); }
});
Routes with Schema Validation
// src/routes/articles/schema.js — JSON Schema definitions
export const articleSchema = {
type: 'object',
properties: {
id: { type: 'integer' },
title: { type: 'string' },
body: { type: 'string' },
createdAt: { type: 'string', format: 'date-time' },
},
};
export const createArticleSchema = {
body: {
type: 'object',
required: ['title', 'body'],
properties: {
title: { type: 'string', maxLength: 200 },
body: { type: 'string' },
},
},
response: { 201: articleSchema },
};
// src/routes/articles/index.js — article CRUD routes
import { createArticleSchema } from './schema.js';
export default async function articleRoutes(fastify) {
fastify.get('/', async (request) => {
const { page = 1, limit = 20 } = request.query;
const offset = (page - 1) * limit;
const { rows } = await fastify.db.query(
'SELECT * FROM articles ORDER BY created_at DESC LIMIT $1 OFFSET $2',
[limit, offset]
);
return rows;
});
fastify.get('/:id', async (request, reply) => {
const { rows } = await fastify.db.query('SELECT * FROM articles WHERE id = $1', [request.params.id]);
if (!rows[0]) return reply.notFound();
return rows[0];
});
fastify.post('/', { schema: createArticleSchema, preHandler: [fastify.authenticate] }, async (request, reply) => {
const { title, body } = request.body;
const { rows } = await fastify.db.query(
'INSERT INTO articles (title, body) VALUES ($1, $2) RETURNING *',
[title, body]
);
return reply.code(201).send(rows[0]);
});
}
Plugins
// src/plugins/db.js — database plugin with pg
import fp from 'fastify-plugin';
import pg from 'pg';
export default fp(async function dbPlugin(fastify) {
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
fastify.decorate('db', pool);
fastify.addHook('onClose', () => pool.end());
});
// src/plugins/auth.js — JWT auth plugin
import fp from 'fastify-plugin';
import jwt from '@fastify/jwt';
export default fp(async function authPlugin(fastify) {
fastify.register(jwt, { secret: process.env.JWT_SECRET || 'dev-secret' });
fastify.decorate('authenticate', async function (request, reply) {
try {
await request.jwtVerify();
} catch (err) {
reply.unauthorized();
}
});
});
Hooks
// src/app.js — lifecycle hooks example (add inside buildApp)
app.addHook('onRequest', async (request) => {
request.startTime = process.hrtime.bigint();
});
app.addHook('onResponse', async (request, reply) => {
const duration = Number(process.hrtime.bigint() - request.startTime) / 1e6;
request.log.info({ duration: `${duration.toFixed(2)}ms`, status: reply.statusCode }, 'request completed');
});
Error Handling
// src/app.js — custom error handler (add inside buildApp)
app.setErrorHandler((error, request, reply) => {
request.log.error(error);
const status = error.statusCode || 500;
reply.code(status).send({
error: error.name,
message: status === 500 ? 'Internal Server Error' : error.message,
});
});
Testing
// src/test/articles.test.js — testing with built-in inject
import { test } from 'node:test';
import assert from 'node:assert';
import { buildApp } from '../app.js';
test('GET /api/articles returns 200', async () => {
const app = buildApp({ logger: false });
const response = await app.inject({ method: 'GET', url: '/api/articles' });
assert.strictEqual(response.statusCode, 200);
await app.close();
});
Key Patterns
- Use
fastify-plugin(fp) for plugins that should share the same encapsulation context - Use JSON Schema for validation — it also generates automatic serialization for speed
- Use
@fastify/autoloadto auto-register plugins and routes from directories - Decorate the fastify instance (
fastify.decorate) for shared services (db, cache) - Use
@fastify/sensiblefor.notFound(),.unauthorized(), etc. helpers - Fastify is async-first: return values from handlers instead of calling
reply.send()
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供完整的 Fastify 项目模板和最佳实践指南
- 涵盖从安装、项目结构到路由、插件、钩子、错误处理和测试的全流程
- 针对 Node.js API 开发的高频刚需场景,实用价值极高
Highlights
- description 精准描述 Fastify 框架的核心特性(高性能、JSON Schema 验证、插件系统)
- 明确说明适用场景(构建极速 API),触发边界清晰
Highlights
- 文档结构清晰,分 Installation、Project Structure、App Setup、Routes、Plugins、Hooks、Error Handling、Testing 等模块
- 每个模块都有完整的代码示例和说明,便于理解和执行
- frontmatter 完整,包含 name、description、license、compatibility、metadata 等信息
Highlights
- 所有代码示例都提供了完整的实现,工具来源明确(如 @fastify/autoload、@fastify/sensible 等)
- 覆盖了主要异常处理(如数据库查询失败、JWT 验证失败等)
- 提供了测试示例,确保代码的可测试性和可靠性
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 32
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.