[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XRDZKANDXKDCKG1MGBSRF":3,"skill-same:01M72XRDZKANDXKDCKG1MGBSRF":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XRDZKANDXKDCKG1MGBSRF","nodejs-backend-patterns",null,"Build production-ready Node.js backend services with Express\u002FFastify, 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.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fnodejs-backend-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: nodejs-backend-patterns\ndescription: Build production-ready Node.js backend services with Express\u002FFastify, 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.\n---\n\n# Node.js Backend Patterns\n\nComprehensive guidance for building scalable, maintainable, and production-ready Node.js backend applications with modern frameworks, architectural patterns, and best practices.\n\n## When to Use This Skill\n\n- Building REST APIs or GraphQL servers\n- Creating microservices with Node.js\n- Implementing authentication and authorization\n- Designing scalable backend architectures\n- Setting up middleware and error handling\n- Integrating databases (SQL and NoSQL)\n- Building real-time applications with WebSockets\n- Implementing background job processing\n\n## Core Frameworks\n\n### Express.js - Minimalist Framework\n\n**Basic Setup:**\n\n```typescript\nimport express, { Request, Response, NextFunction } from \"express\";\nimport helmet from \"helmet\";\nimport cors from \"cors\";\nimport compression from \"compression\";\n\nconst app = express();\n\n\u002F\u002F Security middleware\napp.use(helmet());\napp.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(\",\") }));\napp.use(compression());\n\n\u002F\u002F Body parsing\napp.use(express.json({ limit: \"10mb\" }));\napp.use(express.urlencoded({ extended: true, limit: \"10mb\" }));\n\n\u002F\u002F Request logging\napp.use((req: Request, res: Response, next: NextFunction) => {\n  console.log(`${req.method} ${req.path}`);\n  next();\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on port ${PORT}`);\n});\n```\n\n### Fastify - High Performance Framework\n\n**Basic Setup:**\n\n```typescript\nimport Fastify from \"fastify\";\nimport helmet from \"@fastify\u002Fhelmet\";\nimport cors from \"@fastify\u002Fcors\";\nimport compress from \"@fastify\u002Fcompress\";\n\nconst fastify = Fastify({\n  logger: {\n    level: process.env.LOG_LEVEL || \"info\",\n    transport: {\n      target: \"pino-pretty\",\n      options: { colorize: true },\n    },\n  },\n});\n\n\u002F\u002F Plugins\nawait fastify.register(helmet);\nawait fastify.register(cors, { origin: true });\nawait fastify.register(compress);\n\n\u002F\u002F Type-safe routes with schema validation\nfastify.post\u003C{\n  Body: { name: string; email: string };\n  Reply: { id: string; name: string };\n}>(\n  \"\u002Fusers\",\n  {\n    schema: {\n      body: {\n        type: \"object\",\n        required: [\"name\", \"email\"],\n        properties: {\n          name: { type: \"string\", minLength: 1 },\n          email: { type: \"string\", format: \"email\" },\n        },\n      },\n    },\n  },\n  async (request, reply) => {\n    const { name, email } = request.body;\n    return { id: \"123\", name };\n  },\n);\n\nawait fastify.listen({ port: 3000, host: \"0.0.0.0\" });\n```\n\n## Architectural Patterns\n\n### Pattern 1: Layered Architecture\n\n**Structure:**\n\n```\nsrc\u002F\n├── controllers\u002F     # Handle HTTP requests\u002Fresponses\n├── services\u002F        # Business logic\n├── repositories\u002F    # Data access layer\n├── models\u002F          # Data models\n├── middleware\u002F      # Express\u002FFastify middleware\n├── routes\u002F          # Route definitions\n├── utils\u002F           # Helper functions\n├── config\u002F          # Configuration\n└── types\u002F           # TypeScript types\n```\n\n**Controller Layer:**\n\n```typescript\n\u002F\u002F controllers\u002Fuser.controller.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { UserService } from \"..\u002Fservices\u002Fuser.service\";\nimport { CreateUserDTO, UpdateUserDTO } from \"..\u002Ftypes\u002Fuser.types\";\n\nexport class UserController {\n  constructor(private userService: UserService) {}\n\n  async createUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const userData: CreateUserDTO = req.body;\n      const user = await this.userService.createUser(userData);\n      res.status(201).json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async getUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      const user = await this.userService.getUserById(id);\n      res.json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async updateUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      const updates: UpdateUserDTO = req.body;\n      const user = await this.userService.updateUser(id, updates);\n      res.json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async deleteUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      await this.userService.deleteUser(id);\n      res.status(204).send();\n    } catch (error) {\n      next(error);\n    }\n  }\n}\n```\n\n**Service Layer:**\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nimport { UserRepository } from \"..\u002Frepositories\u002Fuser.repository\";\nimport { CreateUserDTO, UpdateUserDTO, User } from \"..\u002Ftypes\u002Fuser.types\";\nimport { NotFoundError, ValidationError } from \"..\u002Futils\u002Ferrors\";\nimport bcrypt from \"bcrypt\";\n\nexport class UserService {\n  constructor(private userRepository: UserRepository) {}\n\n  async createUser(userData: CreateUserDTO): Promise\u003CUser> {\n    \u002F\u002F Validation\n    const existingUser = await this.userRepository.findByEmail(userData.email);\n    if (existingUser) {\n      throw new ValidationError(\"Email already exists\");\n    }\n\n    \u002F\u002F Hash password\n    const hashedPassword = await bcrypt.hash(userData.password, 10);\n\n    \u002F\u002F Create user\n    const user = await this.userRepository.create({\n      ...userData,\n      password: hashedPassword,\n    });\n\n    \u002F\u002F Remove password from response\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async getUserById(id: string): Promise\u003CUser> {\n    const user = await this.userRepository.findById(id);\n    if (!user) {\n      throw new NotFoundError(\"User not found\");\n    }\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async updateUser(id: string, updates: UpdateUserDTO): Promise\u003CUser> {\n    const user = await this.userRepository.update(id, updates);\n    if (!user) {\n      throw new NotFoundError(\"User not found\");\n    }\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async deleteUser(id: string): Promise\u003Cvoid> {\n    const deleted = await this.userRepository.delete(id);\n    if (!deleted) {\n      throw new NotFoundError(\"User not found\");\n    }\n  }\n}\n```\n\n**Repository Layer:**\n\n```typescript\n\u002F\u002F repositories\u002Fuser.repository.ts\nimport { Pool } from \"pg\";\nimport { CreateUserDTO, UpdateUserDTO, UserEntity } from \"..\u002Ftypes\u002Fuser.types\";\n\nexport class UserRepository {\n  constructor(private db: Pool) {}\n\n  async create(\n    userData: CreateUserDTO & { password: string },\n  ): Promise\u003CUserEntity> {\n    const query = `\n      INSERT INTO users (name, email, password)\n      VALUES ($1, $2, $3)\n      RETURNING id, name, email, password, created_at, updated_at\n    `;\n    const { rows } = await this.db.query(query, [\n      userData.name,\n      userData.email,\n      userData.password,\n    ]);\n    return rows[0];\n  }\n\n  async findById(id: string): Promise\u003CUserEntity | null> {\n    const query = \"SELECT * FROM users WHERE id = $1\";\n    const { rows } = await this.db.query(query, [id]);\n    return rows[0] || null;\n  }\n\n  async findByEmail(email: string): Promise\u003CUserEntity | null> {\n    const query = \"SELECT * FROM users WHERE email = $1\";\n    const { rows } = await this.db.query(query, [email]);\n    return rows[0] || null;\n  }\n\n  async update(id: string, updates: UpdateUserDTO): Promise\u003CUserEntity | null> {\n    const fields = Object.keys(updates);\n    const values = Object.values(updates);\n\n    const setClause = fields\n      .map((field, idx) => `${field} = $${idx + 2}`)\n      .join(\", \");\n\n    const query = `\n      UPDATE users\n      SET ${setClause}, updated_at = CURRENT_TIMESTAMP\n      WHERE id = $1\n      RETURNING *\n    `;\n\n    const { rows } = await this.db.query(query, [id, ...values]);\n    return rows[0] || null;\n  }\n\n  async delete(id: string): Promise\u003Cboolean> {\n    const query = \"DELETE FROM users WHERE id = $1\";\n    const { rowCount } = await this.db.query(query, [id]);\n    return rowCount > 0;\n  }\n}\n```\n\n### Pattern 2: Dependency Injection\n\nUse a DI container to wire up repositories, services, and controllers. For a full container implementation, see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Middleware Patterns\n\n### Authentication Middleware\n\n```typescript\n\u002F\u002F middleware\u002Fauth.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport jwt from \"jsonwebtoken\";\nimport { UnauthorizedError } from \"..\u002Futils\u002Ferrors\";\n\ninterface JWTPayload {\n  userId: string;\n  email: string;\n}\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      user?: JWTPayload;\n    }\n  }\n}\n\nexport const authenticate = async (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  try {\n    const token = req.headers.authorization?.replace(\"Bearer \", \"\");\n\n    if (!token) {\n      throw new UnauthorizedError(\"No token provided\");\n    }\n\n    const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;\n\n    req.user = payload;\n    next();\n  } catch (error) {\n    next(new UnauthorizedError(\"Invalid token\"));\n  }\n};\n\nexport const authorize = (...roles: string[]) => {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return next(new UnauthorizedError(\"Not authenticated\"));\n    }\n\n    \u002F\u002F Check if user has required role\n    const hasRole = roles.some((role) => req.user?.roles?.includes(role));\n\n    if (!hasRole) {\n      return next(new UnauthorizedError(\"Insufficient permissions\"));\n    }\n\n    next();\n  };\n};\n```\n\n### Validation Middleware\n\n```typescript\n\u002F\u002F middleware\u002Fvalidation.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { AnyZodObject, ZodError } from \"zod\";\nimport { ValidationError } from \"..\u002Futils\u002Ferrors\";\n\nexport const validate = (schema: AnyZodObject) => {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    try {\n      await schema.parseAsync({\n        body: req.body,\n        query: req.query,\n        params: req.params,\n      });\n      next();\n    } catch (error) {\n      if (error instanceof ZodError) {\n        const errors = error.errors.map((err) => ({\n          field: err.path.join(\".\"),\n          message: err.message,\n        }));\n        next(new ValidationError(\"Validation failed\", errors));\n      } else {\n        next(error);\n      }\n    }\n  };\n};\n\n\u002F\u002F Usage with Zod\nimport { z } from \"zod\";\n\nconst createUserSchema = z.object({\n  body: z.object({\n    name: z.string().min(1),\n    email: z.string().email(),\n    password: z.string().min(8),\n  }),\n});\n\nrouter.post(\"\u002Fusers\", validate(createUserSchema), userController.createUser);\n```\n\n### Rate Limiting Middleware\n\n```typescript\n\u002F\u002F middleware\u002Frate-limit.middleware.ts\nimport rateLimit from \"express-rate-limit\";\nimport RedisStore from \"rate-limit-redis\";\nimport Redis from \"ioredis\";\n\nconst redis = new Redis({\n  host: process.env.REDIS_HOST,\n  port: parseInt(process.env.REDIS_PORT || \"6379\"),\n});\n\nexport const apiLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: \"rl:\",\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 100, \u002F\u002F Limit each IP to 100 requests per windowMs\n  message: \"Too many requests from this IP, please try again later\",\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\nexport const authLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: \"rl:auth:\",\n  }),\n  windowMs: 15 * 60 * 1000,\n  max: 5, \u002F\u002F Stricter limit for auth endpoints\n  skipSuccessfulRequests: true,\n});\n```\n\n### Request Logging Middleware\n\n```typescript\n\u002F\u002F middleware\u002Flogger.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport pino from \"pino\";\n\nconst logger = pino({\n  level: process.env.LOG_LEVEL || \"info\",\n  transport: {\n    target: \"pino-pretty\",\n    options: { colorize: true },\n  },\n});\n\nexport const requestLogger = (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  const start = Date.now();\n\n  \u002F\u002F Log response when finished\n  res.on(\"finish\", () => {\n    const duration = Date.now() - start;\n    logger.info({\n      method: req.method,\n      url: req.url,\n      status: res.statusCode,\n      duration: `${duration}ms`,\n      userAgent: req.headers[\"user-agent\"],\n      ip: req.ip,\n    });\n  });\n\n  next();\n};\n\nexport { logger };\n```\n\n## Error Handling\n\n### Custom Error Classes\n\n```typescript\n\u002F\u002F utils\u002Ferrors.ts\nexport class AppError extends Error {\n  constructor(\n    public message: string,\n    public statusCode: number = 500,\n    public isOperational: boolean = true,\n  ) {\n    super(message);\n    Object.setPrototypeOf(this, AppError.prototype);\n    Error.captureStackTrace(this, this.constructor);\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(\n    message: string,\n    public errors?: any[],\n  ) {\n    super(message, 400);\n  }\n}\n\nexport class NotFoundError extends AppError {\n  constructor(message: string = \"Resource not found\") {\n    super(message, 404);\n  }\n}\n\nexport class UnauthorizedError extends AppError {\n  constructor(message: string = \"Unauthorized\") {\n    super(message, 401);\n  }\n}\n\nexport class ForbiddenError extends AppError {\n  constructor(message: string = \"Forbidden\") {\n    super(message, 403);\n  }\n}\n\nexport class ConflictError extends AppError {\n  constructor(message: string) {\n    super(message, 409);\n  }\n}\n```\n\n### Global Error Handler\n\n```typescript\n\u002F\u002F middleware\u002Ferror-handler.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { AppError } from \"..\u002Futils\u002Ferrors\";\nimport { logger } from \".\u002Flogger.middleware\";\n\nexport const errorHandler = (\n  err: Error,\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  if (err instanceof AppError) {\n    return res.status(err.statusCode).json({\n      status: \"error\",\n      message: err.message,\n      ...(err instanceof ValidationError && { errors: err.errors }),\n    });\n  }\n\n  \u002F\u002F Log unexpected errors\n  logger.error({\n    error: err.message,\n    stack: err.stack,\n    url: req.url,\n    method: req.method,\n  });\n\n  \u002F\u002F Don't leak error details in production\n  const message =\n    process.env.NODE_ENV === \"production\"\n      ? \"Internal server error\"\n      : err.message;\n\n  res.status(500).json({\n    status: \"error\",\n    message,\n  });\n};\n\n\u002F\u002F Async error wrapper\nexport const asyncHandler = (\n  fn: (req: Request, res: Response, next: NextFunction) => Promise\u003Cany>,\n) => {\n  return (req: Request, res: Response, next: NextFunction) => {\n    Promise.resolve(fn(req, res, next)).catch(next);\n  };\n};\n```\n\n## Database Patterns\n\nNode.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.\n\nKey patterns covered in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md):\n- **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown\n- **MongoDB with Mongoose** — connection management and schema definition\n- **Transaction pattern** — `BEGIN`\u002F`COMMIT`\u002F`ROLLBACK` with `pg` client\n\n## Authentication & Authorization\n\nJWT-based auth with access tokens (short-lived, 15m) and refresh tokens (7d). Full `AuthService` implementation with `bcrypt` password comparison in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Caching Strategies\n\nRedis-backed `CacheService` with get\u002Fset\u002Fdelete\u002FinvalidatePattern, plus a `@Cacheable` decorator for method-level caching. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## API Response Format\n\nStandardized `ApiResponse` helper with `success`, `error`, and `paginated` static methods. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Best Practices\n\n1. **Use TypeScript**: Type safety prevents runtime errors\n2. **Implement proper error handling**: Use custom error classes\n3. **Validate input**: Use libraries like Zod or Joi\n4. **Use environment variables**: Never hardcode secrets\n5. **Implement logging**: Use structured logging (Pino, Winston)\n6. **Add rate limiting**: Prevent abuse\n7. **Use HTTPS**: Always in production\n8. **Implement CORS properly**: Don't use `*` in production\n9. **Use dependency injection**: Easier testing and maintenance\n10. **Write tests**: Unit, integration, and E2E tests\n11. **Handle graceful shutdown**: Clean up resources\n12. **Use connection pooling**: For databases\n13. **Implement health checks**: For monitoring\n14. **Use compression**: Reduce response size\n15. **Monitor performance**: Use APM tools\n\n## Testing Patterns\n\nSee `javascript-testing-patterns` skill for comprehensive testing guidance.\n","# Node.js Backend Patterns\n\nComprehensive guidance for building scalable, maintainable, and production-ready Node.js backend applications with modern frameworks, architectural patterns, and best practices.\n\n## When to Use This Skill\n\n- Building REST APIs or GraphQL servers\n- Creating microservices with Node.js\n- Implementing authentication and authorization\n- Designing scalable backend architectures\n- Setting up middleware and error handling\n- Integrating databases (SQL and NoSQL)\n- Building real-time applications with WebSockets\n- Implementing background job processing\n\n## Core Frameworks\n\n### Express.js - Minimalist Framework\n\n**Basic Setup:**\n\n```typescript\nimport express, { Request, Response, NextFunction } from \"express\";\nimport helmet from \"helmet\";\nimport cors from \"cors\";\nimport compression from \"compression\";\n\nconst app = express();\n\n\u002F\u002F Security middleware\napp.use(helmet());\napp.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(\",\") }));\napp.use(compression());\n\n\u002F\u002F Body parsing\napp.use(express.json({ limit: \"10mb\" }));\napp.use(express.urlencoded({ extended: true, limit: \"10mb\" }));\n\n\u002F\u002F Request logging\napp.use((req: Request, res: Response, next: NextFunction) => {\n  console.log(`${req.method} ${req.path}`);\n  next();\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on port ${PORT}`);\n});\n```\n\n### Fastify - High Performance Framework\n\n**Basic Setup:**\n\n```typescript\nimport Fastify from \"fastify\";\nimport helmet from \"@fastify\u002Fhelmet\";\nimport cors from \"@fastify\u002Fcors\";\nimport compress from \"@fastify\u002Fcompress\";\n\nconst fastify = Fastify({\n  logger: {\n    level: process.env.LOG_LEVEL || \"info\",\n    transport: {\n      target: \"pino-pretty\",\n      options: { colorize: true },\n    },\n  },\n});\n\n\u002F\u002F Plugins\nawait fastify.register(helmet);\nawait fastify.register(cors, { origin: true });\nawait fastify.register(compress);\n\n\u002F\u002F Type-safe routes with schema validation\nfastify.post\u003C{\n  Body: { name: string; email: string };\n  Reply: { id: string; name: string };\n}>(\n  \"\u002Fusers\",\n  {\n    schema: {\n      body: {\n        type: \"object\",\n        required: [\"name\", \"email\"],\n        properties: {\n          name: { type: \"string\", minLength: 1 },\n          email: { type: \"string\", format: \"email\" },\n        },\n      },\n    },\n  },\n  async (request, reply) => {\n    const { name, email } = request.body;\n    return { id: \"123\", name };\n  },\n);\n\nawait fastify.listen({ port: 3000, host: \"0.0.0.0\" });\n```\n\n## Architectural Patterns\n\n### Pattern 1: Layered Architecture\n\n**Structure:**\n\n```\nsrc\u002F\n├── controllers\u002F     # Handle HTTP requests\u002Fresponses\n├── services\u002F        # Business logic\n├── repositories\u002F    # Data access layer\n├── models\u002F          # Data models\n├── middleware\u002F      # Express\u002FFastify middleware\n├── routes\u002F          # Route definitions\n├── utils\u002F           # Helper functions\n├── config\u002F          # Configuration\n└── types\u002F           # TypeScript types\n```\n\n**Controller Layer:**\n\n```typescript\n\u002F\u002F controllers\u002Fuser.controller.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { UserService } from \"..\u002Fservices\u002Fuser.service\";\nimport { CreateUserDTO, UpdateUserDTO } from \"..\u002Ftypes\u002Fuser.types\";\n\nexport class UserController {\n  constructor(private userService: UserService) {}\n\n  async createUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const userData: CreateUserDTO = req.body;\n      const user = await this.userService.createUser(userData);\n      res.status(201).json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async getUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      const user = await this.userService.getUserById(id);\n      res.json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async updateUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      const updates: UpdateUserDTO = req.body;\n      const user = await this.userService.updateUser(id, updates);\n      res.json(user);\n    } catch (error) {\n      next(error);\n    }\n  }\n\n  async deleteUser(req: Request, res: Response, next: NextFunction) {\n    try {\n      const { id } = req.params;\n      await this.userService.deleteUser(id);\n      res.status(204).send();\n    } catch (error) {\n      next(error);\n    }\n  }\n}\n```\n\n**Service Layer:**\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nimport { UserRepository } from \"..\u002Frepositories\u002Fuser.repository\";\nimport { CreateUserDTO, UpdateUserDTO, User } from \"..\u002Ftypes\u002Fuser.types\";\nimport { NotFoundError, ValidationError } from \"..\u002Futils\u002Ferrors\";\nimport bcrypt from \"bcrypt\";\n\nexport class UserService {\n  constructor(private userRepository: UserRepository) {}\n\n  async createUser(userData: CreateUserDTO): Promise\u003CUser> {\n    \u002F\u002F Validation\n    const existingUser = await this.userRepository.findByEmail(userData.email);\n    if (existingUser) {\n      throw new ValidationError(\"Email already exists\");\n    }\n\n    \u002F\u002F Hash password\n    const hashedPassword = await bcrypt.hash(userData.password, 10);\n\n    \u002F\u002F Create user\n    const user = await this.userRepository.create({\n      ...userData,\n      password: hashedPassword,\n    });\n\n    \u002F\u002F Remove password from response\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async getUserById(id: string): Promise\u003CUser> {\n    const user = await this.userRepository.findById(id);\n    if (!user) {\n      throw new NotFoundError(\"User not found\");\n    }\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async updateUser(id: string, updates: UpdateUserDTO): Promise\u003CUser> {\n    const user = await this.userRepository.update(id, updates);\n    if (!user) {\n      throw new NotFoundError(\"User not found\");\n    }\n    const { password, ...userWithoutPassword } = user;\n    return userWithoutPassword as User;\n  }\n\n  async deleteUser(id: string): Promise\u003Cvoid> {\n    const deleted = await this.userRepository.delete(id);\n    if (!deleted) {\n      throw new NotFoundError(\"User not found\");\n    }\n  }\n}\n```\n\n**Repository Layer:**\n\n```typescript\n\u002F\u002F repositories\u002Fuser.repository.ts\nimport { Pool } from \"pg\";\nimport { CreateUserDTO, UpdateUserDTO, UserEntity } from \"..\u002Ftypes\u002Fuser.types\";\n\nexport class UserRepository {\n  constructor(private db: Pool) {}\n\n  async create(\n    userData: CreateUserDTO & { password: string },\n  ): Promise\u003CUserEntity> {\n    const query = `\n      INSERT INTO users (name, email, password)\n      VALUES ($1, $2, $3)\n      RETURNING id, name, email, password, created_at, updated_at\n    `;\n    const { rows } = await this.db.query(query, [\n      userData.name,\n      userData.email,\n      userData.password,\n    ]);\n    return rows[0];\n  }\n\n  async findById(id: string): Promise\u003CUserEntity | null> {\n    const query = \"SELECT * FROM users WHERE id = $1\";\n    const { rows } = await this.db.query(query, [id]);\n    return rows[0] || null;\n  }\n\n  async findByEmail(email: string): Promise\u003CUserEntity | null> {\n    const query = \"SELECT * FROM users WHERE email = $1\";\n    const { rows } = await this.db.query(query, [email]);\n    return rows[0] || null;\n  }\n\n  async update(id: string, updates: UpdateUserDTO): Promise\u003CUserEntity | null> {\n    const fields = Object.keys(updates);\n    const values = Object.values(updates);\n\n    const setClause = fields\n      .map((field, idx) => `${field} = $${idx + 2}`)\n      .join(\", \");\n\n    const query = `\n      UPDATE users\n      SET ${setClause}, updated_at = CURRENT_TIMESTAMP\n      WHERE id = $1\n      RETURNING *\n    `;\n\n    const { rows } = await this.db.query(query, [id, ...values]);\n    return rows[0] || null;\n  }\n\n  async delete(id: string): Promise\u003Cboolean> {\n    const query = \"DELETE FROM users WHERE id = $1\";\n    const { rowCount } = await this.db.query(query, [id]);\n    return rowCount > 0;\n  }\n}\n```\n\n### Pattern 2: Dependency Injection\n\nUse a DI container to wire up repositories, services, and controllers. For a full container implementation, see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Middleware Patterns\n\n### Authentication Middleware\n\n```typescript\n\u002F\u002F middleware\u002Fauth.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport jwt from \"jsonwebtoken\";\nimport { UnauthorizedError } from \"..\u002Futils\u002Ferrors\";\n\ninterface JWTPayload {\n  userId: string;\n  email: string;\n}\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      user?: JWTPayload;\n    }\n  }\n}\n\nexport const authenticate = async (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  try {\n    const token = req.headers.authorization?.replace(\"Bearer \", \"\");\n\n    if (!token) {\n      throw new UnauthorizedError(\"No token provided\");\n    }\n\n    const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;\n\n    req.user = payload;\n    next();\n  } catch (error) {\n    next(new UnauthorizedError(\"Invalid token\"));\n  }\n};\n\nexport const authorize = (...roles: string[]) => {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    if (!req.user) {\n      return next(new UnauthorizedError(\"Not authenticated\"));\n    }\n\n    \u002F\u002F Check if user has required role\n    const hasRole = roles.some((role) => req.user?.roles?.includes(role));\n\n    if (!hasRole) {\n      return next(new UnauthorizedError(\"Insufficient permissions\"));\n    }\n\n    next();\n  };\n};\n```\n\n### Validation Middleware\n\n```typescript\n\u002F\u002F middleware\u002Fvalidation.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { AnyZodObject, ZodError } from \"zod\";\nimport { ValidationError } from \"..\u002Futils\u002Ferrors\";\n\nexport const validate = (schema: AnyZodObject) => {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    try {\n      await schema.parseAsync({\n        body: req.body,\n        query: req.query,\n        params: req.params,\n      });\n      next();\n    } catch (error) {\n      if (error instanceof ZodError) {\n        const errors = error.errors.map((err) => ({\n          field: err.path.join(\".\"),\n          message: err.message,\n        }));\n        next(new ValidationError(\"Validation failed\", errors));\n      } else {\n        next(error);\n      }\n    }\n  };\n};\n\n\u002F\u002F Usage with Zod\nimport { z } from \"zod\";\n\nconst createUserSchema = z.object({\n  body: z.object({\n    name: z.string().min(1),\n    email: z.string().email(),\n    password: z.string().min(8),\n  }),\n});\n\nrouter.post(\"\u002Fusers\", validate(createUserSchema), userController.createUser);\n```\n\n### Rate Limiting Middleware\n\n```typescript\n\u002F\u002F middleware\u002Frate-limit.middleware.ts\nimport rateLimit from \"express-rate-limit\";\nimport RedisStore from \"rate-limit-redis\";\nimport Redis from \"ioredis\";\n\nconst redis = new Redis({\n  host: process.env.REDIS_HOST,\n  port: parseInt(process.env.REDIS_PORT || \"6379\"),\n});\n\nexport const apiLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: \"rl:\",\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 100, \u002F\u002F Limit each IP to 100 requests per windowMs\n  message: \"Too many requests from this IP, please try again later\",\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\nexport const authLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: \"rl:auth:\",\n  }),\n  windowMs: 15 * 60 * 1000,\n  max: 5, \u002F\u002F Stricter limit for auth endpoints\n  skipSuccessfulRequests: true,\n});\n```\n\n### Request Logging Middleware\n\n```typescript\n\u002F\u002F middleware\u002Flogger.middleware.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport pino from \"pino\";\n\nconst logger = pino({\n  level: process.env.LOG_LEVEL || \"info\",\n  transport: {\n    target: \"pino-pretty\",\n    options: { colorize: true },\n  },\n});\n\nexport const requestLogger = (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  const start = Date.now();\n\n  \u002F\u002F Log response when finished\n  res.on(\"finish\", () => {\n    const duration = Date.now() - start;\n    logger.info({\n      method: req.method,\n      url: req.url,\n      status: res.statusCode,\n      duration: `${duration}ms`,\n      userAgent: req.headers[\"user-agent\"],\n      ip: req.ip,\n    });\n  });\n\n  next();\n};\n\nexport { logger };\n```\n\n## Error Handling\n\n### Custom Error Classes\n\n```typescript\n\u002F\u002F utils\u002Ferrors.ts\nexport class AppError extends Error {\n  constructor(\n    public message: string,\n    public statusCode: number = 500,\n    public isOperational: boolean = true,\n  ) {\n    super(message);\n    Object.setPrototypeOf(this, AppError.prototype);\n    Error.captureStackTrace(this, this.constructor);\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(\n    message: string,\n    public errors?: any[],\n  ) {\n    super(message, 400);\n  }\n}\n\nexport class NotFoundError extends AppError {\n  constructor(message: string = \"Resource not found\") {\n    super(message, 404);\n  }\n}\n\nexport class UnauthorizedError extends AppError {\n  constructor(message: string = \"Unauthorized\") {\n    super(message, 401);\n  }\n}\n\nexport class ForbiddenError extends AppError {\n  constructor(message: string = \"Forbidden\") {\n    super(message, 403);\n  }\n}\n\nexport class ConflictError extends AppError {\n  constructor(message: string) {\n    super(message, 409);\n  }\n}\n```\n\n### Global Error Handler\n\n```typescript\n\u002F\u002F middleware\u002Ferror-handler.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport { AppError } from \"..\u002Futils\u002Ferrors\";\nimport { logger } from \".\u002Flogger.middleware\";\n\nexport const errorHandler = (\n  err: Error,\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) => {\n  if (err instanceof AppError) {\n    return res.status(err.statusCode).json({\n      status: \"error\",\n      message: err.message,\n      ...(err instanceof ValidationError && { errors: err.errors }),\n    });\n  }\n\n  \u002F\u002F Log unexpected errors\n  logger.error({\n    error: err.message,\n    stack: err.stack,\n    url: req.url,\n    method: req.method,\n  });\n\n  \u002F\u002F Don't leak error details in production\n  const message =\n    process.env.NODE_ENV === \"production\"\n      ? \"Internal server error\"\n      : err.message;\n\n  res.status(500).json({\n    status: \"error\",\n    message,\n  });\n};\n\n\u002F\u002F Async error wrapper\nexport const asyncHandler = (\n  fn: (req: Request, res: Response, next: NextFunction) => Promise\u003Cany>,\n) => {\n  return (req: Request, res: Response, next: NextFunction) => {\n    Promise.resolve(fn(req, res, next)).catch(next);\n  };\n};\n```\n\n## Database Patterns\n\nNode.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.\n\nKey patterns covered in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md):\n- **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown\n- **MongoDB with Mongoose** — connection management and schema definition\n- **Transaction pattern** — `BEGIN`\u002F`COMMIT`\u002F`ROLLBACK` with `pg` client\n\n## Authentication & Authorization\n\nJWT-based auth with access tokens (short-lived, 15m) and refresh tokens (7d). Full `AuthService` implementation with `bcrypt` password comparison in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Caching Strategies\n\nRedis-backed `CacheService` with get\u002Fset\u002Fdelete\u002FinvalidatePattern, plus a `@Cacheable` decorator for method-level caching. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## API Response Format\n\nStandardized `ApiResponse` helper with `success`, `error`, and `paginated` static methods. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Best Practices\n\n1. **Use TypeScript**: Type safety prevents runtime errors\n2. **Implement proper error handling**: Use custom error classes\n3. **Validate input**: Use libraries like Zod or Joi\n4. **Use environment variables**: Never hardcode secrets\n5. **Implement logging**: Use structured logging (Pino, Winston)\n6. **Add rate limiting**: Prevent abuse\n7. **Use HTTPS**: Always in production\n8. **Implement CORS properly**: Don't use `*` in production\n9. **Use dependency injection**: Easier testing and maintenance\n10. **Write tests**: Unit, integration, and E2E tests\n11. **Handle graceful shutdown**: Clean up resources\n12. **Use connection pooling**: For databases\n13. **Implement health checks**: For monitoring\n14. **Use compression**: Reduce response size\n15. **Monitor performance**: Use APM tools\n\n## Testing Patterns\n\nSee `javascript-testing-patterns` skill for comprehensive testing guidance.\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fnodejs-backend-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill nodejs-backend-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill nodejs-backend-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill nodejs-backend-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fnodejs-backend-patterns\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002Fadvanced-patterns.md","REFERENCE","参考文档",9405,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fnodejs-backend-patterns\u002Freferences\u002Fadvanced-patterns.md",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]