WHAT: Production-ready Node.js backend patterns - Express/Fastify setup, layered architecture, middleware, error handling, validation, database integration, authentication, and caching. WHEN: User is building REST APIs, setting up Node.js servers, implementing authentication, integrating databases, adding validation/caching, or structuring backend applications. KEYWORDS: nodejs, node, express, fastify, typescript, api, rest, middleware, authentication, jwt, validation, zod, postgres, mongodb, redis, caching, rate limiting, error handling
数据来源:ClawHub。 在 ClawSkills 查看
选择你使用的 Agent
方法一:命令行安装(推荐)
推荐(无需提前安装 clawhub)
npx clawhub@latest --dir ~/.claude/skills install nodejs-patterns或使用 clawhub CLI(需提前安装)
clawhub --dir ~/.claude/skills install nodejs-patterns⚠️ 需要 Node.js 18+,没有 Node?请使用下方方法二直接下载 ZIP。 安装 Node.js →
方法二:手动下载安装(无需 Node)
下载 ZIP,解压后将文件夹放到以下路径,重启 Agent 即可:
安装路径
~/.claude/skills/nodejs-patterns/💡解压后将文件夹放到上方路径,重启 Agent 即可生效
--- model: standard description: | WHAT: Production-ready Node.js backend patterns - Express/Fastify setup, layered architecture, middleware, error handling, validation, database integration, authentication, and caching.
WHEN: User is building REST APIs, setting up Node.js servers, implementing authentication, integrating databases, adding validation/caching, or structuring backend applications.
KEYWORDS: nodejs, node, express, fastify, typescript, api, rest, middleware, authentication, jwt, validation, zod, postgres, mongodb, redis, caching, rate limiting, error handling ---
Patterns for building scalable, maintainable Node.js backend applications with TypeScript.
any type - TypeScript types prevent runtime errorsfs.readFileSync in handlerssrc/
├── controllers/ # Handle HTTP requests/responses
├── services/ # Business logic
├── repositories/ # Data access layer
├── models/ # Data models and types
├── middleware/ # Auth, validation, logging, errors
├── routes/ # Route definitions
├── config/ # Database, cache, env configuration
└── utils/ # Helpers, custom errors, response formatting
Controllers handle HTTP concerns, services contain business logic, repositories abstract data access. Each layer only calls the layer below it.
import express from "express";
import helmet from "helmet";
import cors from "cors";
import compression from "compression";
const app = express();
app.use(helmet());
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(",") }));
app.use(compression());
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
import Fastify from "fastify";
import helmet from "@fastify/helmet";
import cors from "@fastify/cors";
const fastify = Fastify({
logger: { level: process.env.LOG_LEVEL || "info" },
});
await fastify.register(helmet);
await fastify.register(cors, { origin: true });
// Type-safe routes with built-in schema validation
fastify.post<{ Body: { name: string; email: string } }>(
"/users",
{
schema: {
body: {
type: "object",
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" },
},
},
},
},
async (request) => {
const { name, email } = request.body;
return { id: "123", name };
},
);
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 = "Resource not found") { super(message, 404); }
}
export class UnauthorizedError extends AppError {
constructor(message = "Unauthorized") { super(message, 401); }
}
export class ForbiddenError extends AppError {
constructor(message = "Forbidden") { super(message, 403); }
}
import { Request, Response, NextFunction } from "express";
import { AppError, ValidationError } from "../utils/errors";
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 }),
});
}
// Don't leak details in production
const message = process.env.NODE_ENV === "production"
? "Internal server error"
: err.message;
res.status(500).json({ status: "error", message });
};
// Wrap async route handlers to forward errors
export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>,
) => (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
import { AnyZodObject, ZodError } from "zod";
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((e) => ({
field: e.path.join("."),
message: e.message,
}));
next(new ValidationError("Validation failed", errors));
} else {
next(error);
}
}
};
};
// Usage
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);
import jwt from "jsonwebtoken";
interface JWTPayload { userId: string; email: string; }
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");
req.user = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
next();
} catch {
next(new UnauthorizedError("Invalid token"));
}
};
export const authorize = (...roles: string[]) => {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) return next(new UnauthorizedError("Not authenticated"));
if (!roles.some((r) => req.user?.roles?.includes(r))) {
return next(new ForbiddenError("Insufficient permissions"));
}
next();
};
};
export class AuthService {
constructor(private userRepository: UserRepository) {}
async login(email: string, password: string) {
const user = await this.userRepository.findByEmail(email);
if (!user || !(await bcrypt.compare(password, user.password))) {
throw new UnauthorizedError("Invalid credentials");
}
return {
token: jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET!,
{ expiresIn: "15m" },
),
refreshToken: jwt.sign(
{ userId: user.id },
process.env.REFRESH_TOKEN_SECRET!,
{ expiresIn: "7d" },
),
user: { id: user.id, name: user.name, email: user.email },
};
}
}
import { Pool, PoolConfig } from "pg";
...安装 Nodejs Patterns 后,可以对 AI 说这些话来触发它
Help me get started with Nodejs Patterns
Explains what Nodejs Patterns does, walks through the setup, and runs a quick demo based on your current project
Use Nodejs Patterns to wHAT: Production-ready Node
Invokes Nodejs Patterns with the right parameters and returns the result directly in the conversation
What can I do with Nodejs Patterns in my developer & devops workflow?
Lists the top use cases for Nodejs Patterns, with example commands for each scenario
将技能文件夹放到 ~/.claude/skills/nodejs-patterns/ 目录(个人级,所有项目可用),或 .claude/skills/nodejs-patterns/(项目级)。重启 AI 客户端后,用 /nodejs-patterns 主动调用,或让 AI 根据上下文自动发现并使用。
Nodejs Patterns 支持 Claude、Cursor、OpenClaw,可与这些 AI 平台无缝集成,扩展其能力。
Nodejs Patterns 可免费安装使用。请查阅仓库了解许可证信息。
WHAT: Production-ready Node.js backend patterns - Express/Fastify setup, layered architecture, middleware, error handling, validation, database integration, authentication, and caching. WHEN: User is building REST APIs, setting up Node.js servers, implementing authentication, integrating databases, adding validation/caching, or structuring backend applications. KEYWORDS: nodejs, node, express, fastify, typescript, api, rest, middleware, authentication, jwt, validation, zod, postgres, mongodb, redis, caching, rate limiting, error handling
Automate my developer & devops tasks using Nodejs Patterns
Identifies repetitive steps in your workflow and sets up Nodejs Patterns to handle them automatically
Nodejs Patterns 属于「Developer & DevOps」分类,该分类的技能帮助 AI 智能体在此领域执行专业任务。