nodejs-backend-patterns
预览截图
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "nodejs-backend-patterns":https://skillpi.com/zh/skills/deepskill-7618240c43600f4de53d9b446c1bebc262613ae3b76e0fe5a6bd8c7fde9ca1f4。安装前核对上游来源和版本:https://github.com/midudev/autoskills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
使用 Express 或 Fastify 构建生产就绪的 Node.js 后端服务,实现中间件模式、错误处理、身份验证、数据库集成和 API 设计最佳实践。适用于创建 Node.js 服务器、REST API、GraphQL 后端或微服务架构。
介绍来源: third_party · midudev · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 用Express/Fastify构建生产准备的Node.js后端服务,实施中间软件模式,错误处理,认证,数据库集成,API设计最佳做法. 创建Node.js服务器,REST API,GraphQL后端或微服务架构时使用.
- 适合谁
- 构建 REST API 或 GraphQL 服务器 创建带有 Node.js 的微服务 实施认证和授权 设计可扩展后端架构 设置中端软件和错误处理 整合数据库 (SQL 和 NoSQL) 构建带有 WebSockets 执行背景任务处理的实时应用程序
- 实测状态
- 未测试
文件浏览
Frontmatter
name: nodejs-backend-patterns
description: Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.Node.js Backend Patterns
Comprehensive guidance for building scalable, maintainable, and production-ready Node.js backend applications with modern frameworks, architectural patterns, and best practices.
When to Use This Skill
- Building REST APIs or GraphQL servers
- Creating microservices with Node.js
- Implementing authentication and authorization
- Designing scalable backend architectures
- Setting up middleware and error handling
- Integrating databases (SQL and NoSQL)
- Building real-time applications with WebSockets
- Implementing background job processing
Core Frameworks
Express.js - Minimalist Framework
Basic Setup:
import express, { Request, Response, NextFunction } from "express";
import helmet from "helmet";
import cors from "cors";
import compression from "compression";
const app = express();
// Security middleware
app.use(helmet());
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(",") }));
app.use(compression());
// Body parsing
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
// Request logging
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.path}`);
next();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Fastify - High Performance Framework
Basic Setup:
import Fastify from "fastify";
import helmet from "@fastify/helmet";
import cors from "@fastify/cors";
import compress from "@fastify/compress";
const fastify = Fastify({
logger: {
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true },
},
},
});
// Plugins
await fastify.register(helmet);
await fastify.register(cors, { origin: true });
await fastify.register(compress);
// Type-safe routes with schema validation
fastify.post<{
Body: { name: string; email: string };
Reply: { id: string; name: string };
}>(
"/users",
{
schema: {
body: {
type: "object",
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" },
},
},
},
},
async (request, reply) => {
const { name, email } = request.body;
return { id: "123", name };
},
);
await fastify.listen({ port: 3000, host: "0.0.0.0" });
Architectural Patterns
Pattern 1: Layered Architecture
Structure:
src/
├── controllers/ # Handle HTTP requests/responses
├── services/ # Business logic
├── repositories/ # Data access layer
├── models/ # Data models
├── middleware/ # Express/Fastify middleware
├── routes/ # Route definitions
├── utils/ # Helper functions
├── config/ # Configuration
└── types/ # TypeScript types
Controller Layer:
// controllers/user.controller.ts
import { Request, Response, NextFunction } from "express";
import { UserService } from "../services/user.service";
import { CreateUserDTO, UpdateUserDTO } from "../types/user.types";
export class UserController {
constructor(private userService: UserService) {}
async createUser(req: Request, res: Response, next: NextFunction) {
try {
const userData: CreateUserDTO = req.body;
const user = await this.userService.createUser(userData);
res.status(201).json(user);
} catch (error) {
next(error);
}
}
async getUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
const user = await this.userService.getUserById(id);
res.json(user);
} catch (error) {
next(error);
}
}
async updateUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
const updates: UpdateUserDTO = req.body;
const user = await this.userService.updateUser(id, updates);
res.json(user);
} catch (error) {
next(error);
}
}
async deleteUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
await this.userService.deleteUser(id);
res.status(204).send();
} catch (error) {
next(error);
}
}
}
Service Layer:
// services/user.service.ts
import { UserRepository } from "../repositories/user.repository";
import { CreateUserDTO, UpdateUserDTO, User } from "../types/user.types";
import { NotFoundError, ValidationError } from "../utils/errors";
import bcrypt from "bcrypt";
export class UserService {
constructor(private userRepository: UserRepository) {}
async createUser(userData: CreateUserDTO): Promise<User> {
// Validation
const existingUser = await this.userRepository.findByEmail(userData.email);
if (existingUser) {
throw new ValidationError("Email already exists");
}
// Hash password
const hashedPassword = await bcrypt.hash(userData.password, 10);
// Create user
const user = await this.userRepository.create({
...userData,
password: hashedPassword,
});
// Remove password from response
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async getUserById(id: string): Promise<User> {
const user = await this.userRepository.findById(id);
if (!user) {
throw new NotFoundError("User not found");
}
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async updateUser(id: string, updates: UpdateUserDTO): Promise<User> {
const user = await this.userRepository.update(id, updates);
if (!user) {
throw new NotFoundError("User not found");
}
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async deleteUser(id: string): Promise<void> {
const deleted = await this.userRepository.delete(id);
if (!deleted) {
throw new NotFoundError("User not found");
}
}
}
Repository Layer:
// repositories/user.repository.ts
import { Pool } from "pg";
import { CreateUserDTO, UpdateUserDTO, UserEntity } from "../types/user.types";
export class UserRepository {
constructor(private db: Pool) {}
async create(
userData: CreateUserDTO & { password: string },
): Promise<UserEntity> {
const query = `
INSERT INTO users (name, email, password)
VALUES ($1, $2, $3)
RETURNING id, name, email, password, created_at, updated_at
`;
const { rows } = await this.db.query(query, [
userData.name,
userData.email,
userData.password,
]);
return rows[0];
}
async findById(id: string): Promise<UserEntity | null> {
const query = "SELECT * FROM users WHERE id = $1";
const { rows } = await this.db.query(query, [id]);
return rows[0] || null;
}
async findByEmail(email: string): Promise<UserEntity | null> {
const query = "SELECT * FROM users WHERE email = $1";
const { rows } = await this.db.query(query, [email]);
return rows[0] || null;
}
async update(id: string, updates: UpdateUserDTO): Promise<UserEntity | null> {
const fields = Object.keys(updates);
const values = Object.values(updates);
const setClause = fields
.map((field, idx) => `${field} = $${idx + 2}`)
.join(", ");
const query = `
UPDATE users
SET ${setClause}, updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *
`;
const { rows } = await this.db.query(query, [id, ...values]);
return rows[0] || null;
}
async delete(id: string): Promise<boolean> {
const query = "DELETE FROM users WHERE id = $1";
const { rowCount } = await this.db.query(query, [id]);
return rowCount > 0;
}
}
Pattern 2: Dependency Injection
Use a DI container to wire up repositories, services, and controllers. For a full container implementation, see references/advanced-patterns.md.
Middleware Patterns
Authentication Middleware
// middleware/auth.middleware.ts
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { UnauthorizedError } from "../utils/errors";
interface JWTPayload {
userId: string;
email: string;
}
declare global {
namespace Express {
interface Request {
user?: JWTPayload;
}
}
}
export const authenticate = async (
req: Request,
res: Response,
next: NextFunction,
) => {
try {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) {
throw new UnauthorizedError("No token provided");
}
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
req.user = payload;
next();
} catch (error) {
next(new UnauthorizedError("Invalid token"));
}
};
export const authorize = (...roles: string[]) => {
return async (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return next(new UnauthorizedError("Not authenticated"));
}
// Check if user has required role
const hasRole = roles.some((role) => req.user?.roles?.includes(role));
if (!hasRole) {
return next(new UnauthorizedError("Insufficient permissions"));
}
next();
};
};
Validation Middleware
// middleware/validation.middleware.ts
import { Request, Response, NextFunction } from "express";
import { AnyZodObject, ZodError } from "zod";
import { ValidationError } from "../utils/errors";
export const validate = (schema: AnyZodObject) => {
return async (req: Request, res: Response, next: NextFunction) => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
});
next();
} catch (error) {
if (error instanceof ZodError) {
const errors = error.errors.map((err) => ({
field: err.path.join("."),
message: err.message,
}));
next(new ValidationError("Validation failed", errors));
} else {
next(error);
}
}
};
};
// Usage with Zod
import { z } from "zod";
const createUserSchema = z.object({
body: z.object({
name: z.string().min(1),
email: z.string().email(),
password: z.string().min(8),
}),
});
router.post("/users", validate(createUserSchema), userController.createUser);
Rate Limiting Middleware
// middleware/rate-limit.middleware.ts
import rateLimit from "express-rate-limit";
import RedisStore from "rate-limit-redis";
import Redis from "ioredis";
const redis = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT || "6379"),
});
export const apiLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:",
}),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later",
standardHeaders: true,
legacyHeaders: false,
});
export const authLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:auth:",
}),
windowMs: 15 * 60 * 1000,
max: 5, // Stricter limit for auth endpoints
skipSuccessfulRequests: true,
});
Request Logging Middleware
// middleware/logger.middleware.ts
import { Request, Response, NextFunction } from "express";
import pino from "pino";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true },
},
});
export const requestLogger = (
req: Request,
res: Response,
next: NextFunction,
) => {
const start = Date.now();
// Log response when finished
res.on("finish", () => {
const duration = Date.now() - start;
logger.info({
method: req.method,
url: req.url,
status: res.statusCode,
duration: `${duration}ms`,
userAgent: req.headers["user-agent"],
ip: req.ip,
});
});
next();
};
export { logger };
Error Handling
Custom Error Classes
// utils/errors.ts
export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 500,
public isOperational: boolean = true,
) {
super(message);
Object.setPrototypeOf(this, AppError.prototype);
Error.captureStackTrace(this, this.constructor);
}
}
export class ValidationError extends AppError {
constructor(
message: string,
public errors?: any[],
) {
super(message, 400);
}
}
export class NotFoundError extends AppError {
constructor(message: string = "Resource not found") {
super(message, 404);
}
}
export class UnauthorizedError extends AppError {
constructor(message: string = "Unauthorized") {
super(message, 401);
}
}
export class ForbiddenError extends AppError {
constructor(message: string = "Forbidden") {
super(message, 403);
}
}
export class ConflictError extends AppError {
constructor(message: string) {
super(message, 409);
}
}
Global Error Handler
// middleware/error-handler.ts
import { Request, Response, NextFunction } from "express";
import { AppError } from "../utils/errors";
import { logger } from "./logger.middleware";
export const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction,
) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
status: "error",
message: err.message,
...(err instanceof ValidationError && { errors: err.errors }),
});
}
// Log unexpected errors
logger.error({
error: err.message,
stack: err.stack,
url: req.url,
method: req.method,
});
// Don't leak error details in production
const message =
process.env.NODE_ENV === "production"
? "Internal server error"
: err.message;
res.status(500).json({
status: "error",
message,
});
};
// Async error wrapper
export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>,
) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
Database Patterns
Node.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.
Key patterns covered in references/advanced-patterns.md:
- PostgreSQL with connection pool —
pgPool configuration and graceful shutdown - MongoDB with Mongoose — connection management and schema definition
- Transaction pattern —
BEGIN/COMMIT/ROLLBACKwithpgclient
Authentication & Authorization
JWT-based auth with access tokens (short-lived, 15m) and refresh tokens (7d). Full AuthService implementation with bcrypt password comparison in references/advanced-patterns.md.
Caching Strategies
Redis-backed CacheService with get/set/delete/invalidatePattern, plus a @Cacheable decorator for method-level caching. See references/advanced-patterns.md.
API Response Format
Standardized ApiResponse helper with success, error, and paginated static methods. See references/advanced-patterns.md.
Best Practices
- Use TypeScript: Type safety prevents runtime errors
- Implement proper error handling: Use custom error classes
- Validate input: Use libraries like Zod or Joi
- Use environment variables: Never hardcode secrets
- Implement logging: Use structured logging (Pino, Winston)
- Add rate limiting: Prevent abuse
- Use HTTPS: Always in production
- Implement CORS properly: Don't use
*in production - Use dependency injection: Easier testing and maintenance
- Write tests: Unit, integration, and E2E tests
- Handle graceful shutdown: Clean up resources
- Use connection pooling: For databases
- Implement health checks: For monitoring
- Use compression: Reduce response size
- Monitor performance: Use APM tools
Testing Patterns
See javascript-testing-patterns skill for comprehensive testing guidance.
版本历史
-
v0.4.1
GitHub ↗
原版更新说明
### 🐛 Bug Fixes - fix(autoskills): stop multiSelect from duplicating lines on redraw [`cc80891`](https://github.com/midudev/autoskills/commit/cc80891)
-
v0.4.0
GitHub ↗
原版更新说明
### ⚠️ Breaking Changes - refactor(autoskills)!: drop Deno support [`d6f4301`](https://github.com/midudev/autoskills/commit/d6f4301) ### ✨ Features - feat(registry): re-review 41 pending skills with the new pipeline [`aff4e3c`](https://github.com/midudev/autoskills/commit/aff4e3c) - feat(sync): let an AI adjudicate flagged skills instead of a human [`98d42aa`](https://github.com/midudev/autoskills/commit/98d42aa) - fix(registry): add official FastAPI skill and merge duplicate techs [`f58a99c`](https://github.com/midudev/autoskills/commit/f58a99c) - feat(registry): sync skills and drop those removed upstream [`1228788`](https://github.com/midudev/autoskills/commit/1228788) - feat(autoskills): add ui command to browse installed skills [`1e5a14a`](https://github.com/midudev/autoskills/commit/1e5a14a) - Add fastmcp skill for Python MCP server development FastMCP is the standard Python framework for building MCP servers. This skill teaches production patterns verified against FastMCP 3.2.x, specifically addressing APIs that LLMs hallucinate (server.state, on_startup, context.name in middleware — none of which exist). Detection: 'fastmcp' pattern in pyproject.toml/requirements.txt Validation: 97.1% (agentskills.io spec checker) [`8caa407`](https://github.com/midudev/autoskills/commit/8caa407) - feat: add ElysiaJS support with skills registry documentation and icon [`b2e1400`](https://github.com/midudev/autoskills/commit/b2e1400) ### 📦 Other Changes - test(cli): ignore FORCE_COLOR when checking CLI output [`97692cd`](https://github.com/midudev/autoskills/commit/97692cd) - chore(release): skip merge commits in the changelog [`5ba3aa3`](https://github.com/midudev/autoskills/commit/5ba3aa3) - docs: document ui command, missing flags and the AI review [`0ad8885`](https://github.com/midudev/autoskills/commit/0ad8885) - chore(sync): review skills with Claude and accept --only lists [`5740dd0`](https://github.com/midudev/autoskills/commit/5740dd0) - perf(autoskills): download skill files in parallel [`0293487`](https://github.com/midudev/autoskills/commit/0293487) - build(deps): update Astro 7, Tailwind, oxc, TypeScript 7 and pnpm [`18de798`](https://github.com/midudev/autoskills/commit/18de798)
-
v0.3.6
GitHub ↗
原版更新说明
### ✨ Features - feat(autoskills): detect instantdb projects [`c86be97`](https://github.com/midudev/autoskills/commit/c86be97) - feat(autoskills): detect bash scripts [`fe57ba0`](https://github.com/midudev/autoskills/commit/fe57ba0) ### 🐛 Bug Fixes - fix(autoskills): normalize registry paths for downloads [`8477028`](https://github.com/midudev/autoskills/commit/8477028) ### 📦 Other Changes - chore(registry): update synced skill manifest [`442cf12`](https://github.com/midudev/autoskills/commit/442cf12) - chore(registry): sync turborepo skill [`3fadf74`](https://github.com/midudev/autoskills/commit/3fadf74) - chore(registry): sync backend and rails skills [`db3b50b`](https://github.com/midudev/autoskills/commit/db3b50b) - chore(registry): sync frontend and mobile skills [`49550f5`](https://github.com/midudev/autoskills/commit/49550f5)
-
v0.3.5
GitHub ↗
原版更新说明
### ✨ Features - feat(cli): surface skill security warnings [`aba2acf`](https://github.com/midudev/autoskills/commit/aba2acf) - feat(autoskills): display registry security checks [`df77e04`](https://github.com/midudev/autoskills/commit/df77e04) - feat(swiftui): support selecting xctrace runs [`050801e`](https://github.com/midudev/autoskills/commit/050801e) - feat(rails-upgrade): add legacy guide and ci sync workflow [`468fde3`](https://github.com/midudev/autoskills/commit/468fde3) - feat(cloudflare): add flagship feature flag references [`f1b429d`](https://github.com/midudev/autoskills/commit/f1b429d) - feat(azure-diagnostics): add app service and messaging guides [`260ddd4`](https://github.com/midudev/autoskills/commit/260ddd4) - feat(autoskills): add curated Bun skill [`2760757`](https://github.com/midudev/autoskills/commit/2760757) ### 🐛 Bug Fixes - fix(ui): hide single selection group header [`e5c26da`](https://github.com/midudev/autoskills/commit/e5c26da) ### 📦 Other Changes - chore(skills): refresh registry skill guidance [`5d301d5`](https://github.com/midudev/autoskills/commit/5d301d5)
-
v0.3.4
GitHub ↗
原版更新说明
### ✨ Features - feat(autoskills): add verbose install tracing [`cc409f8`](https://github.com/midudev/autoskills/commit/cc409f8) - feat(autoskills): fall back to main registry mirror [`f7d9155`](https://github.com/midudev/autoskills/commit/f7d9155) ### 🐛 Bug Fixes - fix(release): normalize repository URL for changelog and release summary links [`832819e`](https://github.com/midudev/autoskills/commit/832819e) ### 📦 Other Changes - style(autoskills): format code for improved readability [`a5a3f11`](https://github.com/midudev/autoskills/commit/a5a3f11)
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供全面的 Node.js 后端开发模式和最佳实践
- 覆盖 Express 和 Fastify 两大主流框架
- 包含生产就绪的架构设计、中间件、错误处理等核心内容
亮点
- 触发词覆盖全面,包括 REST API、GraphQL、微服务等多种场景
- When to Use 部分提供了清晰的适用场景说明
亮点
- 结构清晰,分层架构明确
- 提供了完整的代码示例和最佳实践
- frontmatter 完整,文档组织良好
亮点
- 提供了完整的错误处理机制和自定义错误类
- 包含输入验证、认证授权、速率限制等可靠性保障
- 工具来源明确,参数配置合理
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。