fastify
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.
What this skill does
# Fastify
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
```bash
# 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
```javascript
// 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;
}
```
```javascript
// 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
```javascript
// 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 },
};
```
```javascript
// 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
```javascript
// 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());
});
```
```javascript
// 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
```javascript
// 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
```javascript
// 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
```javascript
// 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/autoload` to auto-register plugins and routes from directories
- Decorate the fastify instance (`fastify.decorate`) for shared services (db, cache)
- Use `@fastify/sensible` for `.notFound()`, `.unauthorized()`, etc. helpers
- Fastify is async-first: return values from handlers instead of calling `reply.send()`
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.