Skip to content
返回技术栈推荐

Node.js Fastify 后端

高性能 Node.js API:Fastify 5、JSON Schema 验证和 Swagger 自动文档。

API 服务中等

技术栈组成

FrameworkFastify 5
ValidationJSON Schema + ajv
DatabasePostgreSQL + pg
Auth@fastify/jwt + @fastify/auth
Docs@fastify/swagger + @fastify/swagger-ui
DeployDocker + Fly.io

为什么

Fastify 处理 7.6 万 req/s(Express 的 3 倍),基于 schema 的序列化。JSON Schema 一次声明同时验证输入、生成 Swagger 文档和加速序列化。

插件架构保持路由模块化。

何时使用

选择 Fastify 用于高吞吐 REST API、需要 schema 验证的微服务和想要自动文档的团队。避免 GraphQL(用 Mercurius 或 Yoga)或团队被 Express 中间件锁定。

如何做

1. 脚手架 — npm init fastify,选 TypeScript + ESLint 2. 定义 schema — body/params/querystring/response 的 JSON Schema 3. 创建路由 — fastify.post('/users', { schema, handler }),自动验证 4. 插件 — fastify.register(plugin, opts) 注册 db、auth、swagger(封装) 5. JWT 认证 — @fastify/jwt + preHandler 钩子,用 user 装饰 request 6. Swagger — @fastify/swagger + @fastify/swagger-ui,从 schema 自动生成 7. 测试 — tap 或 Vitest,fastify.inject() 进程内请求测试 8. 部署 — Dockerfile(node:20-slim),fly.io deploy 或 k8s 带健康检查

示例

// src/routes/users.ts — schema 验证路由 import { FastifyInstance } from "fastify"; import { Type, Static } from "@fastify/type-provider-typebox"; const UserSchema = Type.Object({ id: Type.String({ format: "uuid" }), email: Type.String({ format: "email" }), name: Type.String({ minLength: 1, maxLength: 100 }), }); type User = Static<typeof UserSchema>; export default async function users(fastify: FastifyInstance) { fastify.post<{ Body: { email: string; name: string }; Reply: User; }>("/users", { schema: { body: Type.Object({ email: Type.String({ format: "email" }), name: Type.String({ minLength: 1 }), }), response: { 201: UserSchema }, }, preHandler: [fastify.authenticate], // JWT 检查 handler: async (req, reply) => { const user = await fastify.db.user.create({ data: req.body }); reply.code(201).send(user); }, }); } // src/app.ts — 插件 + swagger import Fastify from "fastify"; import swagger from "@fastify/swagger"; import swaggerUi from "@fastify/swagger-ui"; import jwt from "@fastify/jwt"; const app = Fastify({ logger: true }); app.register(jwt, { secret: process.env.JWT_SECRET }); app.register(swagger, { openapi: { info: { title: "API", version: "1.0" } } }); app.register(swaggerUi, { routePrefix: "/docs" }); app.register(users); app.decorate("authenticate", async (req: any, reply: any) => { await req.jwtVerify(); }); export default app;

常见问题

  • ⚠Schema 不匹配运行时错误 — 响应不匹配 schema,Fastify 抛错(好!修数据)
  • ⚠插件封装 — 装饰器不泄露到父级,用 fastify-plugin 共享
  • ⚠async handler 无 await — 异步工作前 reply 已发,用 return 或 await
  • ⚠JWT secret 写代码 — 用环境变量,定期轮换,永不提交

最佳实践

  • ✓schema 用 TypeBox — TypeBox 一次生成 JSON Schema + TS 类型
  • ✓用插件封装 — 每个路由文件是插件,作用域装饰器
  • ✓测试用 fastify.inject() — 无端口绑定,比 supertest 快 10 倍
  • ✓启用 schema 序列化 — 响应 schema 让 JSON.stringify 快 2 倍

常见问题解答

什么是Node.js Fastify 后端?适合做什么项目?

高性能 Node.js API:Fastify 5、JSON Schema 验证和 Swagger 自动文档。 它通过分层组合提供端到端类型安全与开箱即用的部署体验,适合从 MVP 到生产 SaaS 的快速迭代。

如何用Node.js Fastify 后端在 10 分钟内跑通一个 demo?

两步起步:① 脚手架 — npm init fastify,选 TypeScript + ESLint;② 定义 schema — body/params/querystring/response 的 JSON Schema。先跑通本地 dev server,再接一个真实数据源验证端到端链路。

Node.js Fastify 后端 最常见的坑是什么?怎么避免?

最高频的坑是:Schema 不匹配运行时错误 — 响应不匹配 schema,Fastify 抛错(好!修数据)。避免方法:在 PR 模板里加入对应 checklist,CI 中跑类型检查 + lint + 单测,三重把关再合并。

Node.js Fastify 后端 的最佳实践有哪些?

Node.js Fastify 后端 的最佳实践包括:schema 用 TypeBox — TypeBox 一次生成 JSON Schema + TS 类型;用插件封装 — 每个路由文件是插件,作用域装饰器;测试用 fastify.inject() — 无端口绑定,比 supertest 快 10 倍。其中首条「schema 用 TypeBox — TypeBox 一次生成 JSON Schema + TS 类型」应在项目初始化时就落地,避免后期返工。

什么情况下不该选Node.js Fastify 后端?

三种情况另选他栈:① 团队对该栈核心框架零经验且工期紧张(学习曲线风险);② 项目是纯内容/营销站(选 Astro 更轻);③ 需要极高吞吐(>1 万 RPS)或强一致微服务(选 Go/Rust)。Node.js Fastify 后端 的强项是中高复杂度全栈与 API,别在简单静态页上过度工程。