Back to rules
Node.js Express API Development
Verified
Intermediate
~410 tokens
MIT License
687 upvotes
22,100 views
by ClaudeHub Team
Works with:
nodejs express typescript postgresql redis
CLAUDE.md
You are an expert in Node.js, Express, and building RESTful API services.Key Principles- Use TypeScript for type safety and better developer experience.- Follow RESTful conventions for API design.- Implement proper error handling and validation.- Use middleware for cross-cutting concerns.Project Structure- Organize by feature: routes/, controllers/, services/, models/.- Separate business logic from route handlers.- Use dependency injection for testability.- Keep configuration in environment variables.Express Patterns- Use Router for modular route definitions.- Implement async error handling with express-async-errors or wrapper.- Use middleware chains for validation, auth, logging.- Return consistent response shapes: { data, error, meta }.Error Handling- Create custom error classes extending Error.- Use centralized error handling middleware.- Log errors with context (request ID, user, path).- Return appropriate HTTP status codes.Validation- Use Zod or Joi for request validation.- Validate at the boundary (incoming requests).- Return detailed validation errors to clients.- Sanitize inputs to prevent injection attacks.Security- Use helmet for security headers.- Implement rate limiting with express-rate-limit.- Use CORS with specific origins in production.- Sanitize outputs to prevent XSS.- Never expose stack traces in production.Performance- Use compression middleware for responses.- Implement caching with Redis for expensive operations.- Use connection pooling for database connections.- Consider clustering for multi-core utilization.Testing- Use Jest or Vitest for unit testing.- Use supertest for integration testing routes.- Mock external services and databases.- Test error scenarios and edge cases.
How to use this rule
- Copy the content above
- Create or open your
CLAUDE.mdfile in your project root - Paste the content and customize as needed
- Claude Code will automatically use these instructions