Skip to content

Node.js Backend Patterns

Master Node.js backend development with Cursor IDE and Claude Code. These patterns cover everything from API design to microservices, database integration, testing strategies, and deployment patterns optimized for AI-assisted development.

  1. Open Cursor in your workspace
  2. Activate Agent mode (Cmd/Ctrl + I)
  3. Prompt: “Use Context7 to get latest Express.js and Prisma documentation. Create a Node.js TypeScript project with:
    • Express.js with type definitions
    • Prisma ORM for database
    • Jest for testing
    • ESLint and Prettier
    • Docker configuration”
  4. Let the agent handle package installation and configuration
// Cursor prompt for clean architecture:
"Set up clean architecture for Node.js with:
- Domain layer (entities, use cases)
- Infrastructure layer (database, external services)
- Application layer (controllers, middleware)
- Presentation layer (DTOs, transformers)
- Dependency injection with tsyringe"
// Generated structure:
src/
domain/
entities/
repositories/
use-cases/
infrastructure/
database/
external/
application/
controllers/
middleware/
presentation/
dtos/
transformers/
// PRD: User Management API
// Requirements: RESTful API with auth, validation, and docs
// Plan: Use Context7 for current Express patterns
// Cursor Agent prompt:
"Use Context7 to research Express.js best practices and JWT authentication.
Create a RESTful API for user management with:
- CRUD operations
- Validation middleware
- Error handling
- Authentication with JWT
- Rate limiting
- OpenAPI documentation
Todo list:
- [ ] Set up Express with TypeScript
- [ ] Create user routes and controllers
- [ ] Implement validation middleware
- [ ] Add JWT authentication
- [ ] Configure rate limiting
- [ ] Generate OpenAPI docs"
// Comprehensive GraphQL prompt:
"Set up GraphQL server with:
- Apollo Server
- Type-graphql decorators
- DataLoader for N+1 prevention
- Subscription support
- Authentication context
- Error handling"
Terminal window
# PRD: E-commerce Database Schema
# Plan: Design normalized schema with Prisma
# Use database MCP for schema insights
"Connect to PostgreSQL MCP and analyze existing database structure if any"
# Use Context7 for Prisma patterns
"Use Context7 to get latest Prisma documentation and best practices"
# Implementation steps:
1. **Schema Design**: "Based on Context7 docs, create Prisma schema for e-commerce with users, products, orders"
2. **Migrations**: "Generate and apply database migrations"
3. **Seed Data**: "Create seed script with realistic test data"
4. **Query Optimization**: "Use PostgreSQL MCP to analyze queries and add indexes"
// Database patterns prompt:
"Implement database connection with:
- Connection pooling
- Retry logic
- Transaction support
- Read/write splitting
- Migration system
- Backup strategies"

AI-Assisted Database Design

Cursor/Claude can help with:

  • Schema normalization
  • Index optimization
  • Query performance analysis
  • Migration strategies
  • Data modeling best practices
// Auth system prompt:
"Implement JWT authentication with:
- Access and refresh tokens
- Role-based access control
- OAuth2 integration (Google, GitHub)
- Session management
- Password reset flow
- 2FA support"

Input Validation

// Prompt: "Add comprehensive validation:
// - Request body validation
// - Query parameter sanitization
// - File upload restrictions
// - SQL injection prevention"

Rate Limiting

// Prompt: "Implement rate limiting:
// - Per-user limits
// - IP-based throttling
// - Distributed rate limiting
// - Custom limit strategies"
// Microservices setup prompt:
"Create microservices architecture with:
- Service discovery
- API gateway
- Inter-service communication
- Distributed tracing
- Circuit breakers
- Event-driven messaging"
// RabbitMQ integration:
"Set up RabbitMQ with:
- Publisher/subscriber pattern
- Work queues
- Dead letter queues
- Connection recovery
- Message acknowledgment"
// PRD: Comprehensive Testing Strategy
// Plan: Implement multi-layer testing
// Use Context7 for testing frameworks
"Use Context7 to get documentation for:
1. Jest best practices
2. Supertest for API testing
3. Database testing strategies"
// Test generation prompt:
"Following TDD principles, create test suite with:
Todo:
- [ ] Unit tests for services
- [ ] Integration tests for APIs
- [ ] E2E tests with Supertest
- [ ] Database transaction tests
- [ ] Mock external services
- [ ] Coverage reporting (min 80%)"
  1. Write Tests First: “Create tests for user registration endpoint”
  2. Implement Code: “Implement user registration to pass tests”
  3. Refactor: “Refactor code while maintaining test coverage”
  4. Add Edge Cases: “Add tests for error scenarios”
// Caching implementation:
"Add caching layer with:
- Redis for session storage
- Query result caching
- CDN integration
- Cache invalidation strategies
- Distributed caching
- Performance monitoring"

Performance Patterns

AI can implement:

  • Database query optimization
  • Connection pooling
  • Lazy loading strategies
  • Resource compression
  • Horizontal scaling patterns
// Logging setup prompt:
"Implement logging system with:
- Winston or Pino logger
- Structured JSON logs
- Log levels and filtering
- Correlation IDs
- Error tracking (Sentry)
- Log aggregation ready"
  1. Metrics Collection: “Set up Prometheus metrics”
  2. Health Checks: “Add health check endpoints”
  3. APM Integration: “Configure Application Performance Monitoring”
  4. Alerting: “Set up alerting rules”
# Docker setup prompt:
"Create Docker configuration with:
- Multi-stage builds
- Layer optimization
- Security best practices
- Environment variables
- Health checks
- Compose for local dev"
# CI/CD prompt: "Create GitHub Actions workflow with:
# - Automated testing
# - Build and push Docker images
# - Deployment to staging/production
# - Rollback mechanisms"
// PRD: Real-time Communication System
// Use Context7 for Socket.io patterns
"Use Context7 to get latest Socket.io documentation and scaling patterns"
// WebSocket implementation plan:
"Create a real-time system with:
Plan:
1. Research Socket.io best practices
2. Design room architecture
3. Implement auth flow
4. Add reconnection handling
Todo:
- [ ] Socket.io setup with TypeScript
- [ ] Room management system
- [ ] JWT-based authentication
- [ ] Reconnection logic with exponential backoff
- [ ] Message broadcasting with acknowledgments
- [ ] Presence tracking with Redis"
// SSE implementation:
"Create SSE endpoint for:
- Live notifications
- Progress updates
- Real-time dashboards
- Automatic reconnection
- Event filtering"
// Error handling prompt:
"Implement error handling with:
- Custom error classes
- Global error middleware
- Async error catching
- Error logging
- User-friendly responses
- Stack trace management"
// Structure prompts like:
"Create [feature] for Node.js with:
- TypeScript support
- Error handling
- Input validation
- Unit tests
- Documentation
Following our existing patterns in [reference files]"

AI-Powered Code Review

Use Cursor/Claude to:

  • Check for security vulnerabilities
  • Verify error handling completeness
  • Optimize database queries
  • Ensure consistent coding patterns
  • Validate API contracts
// PRD: Event Sourcing Implementation
// Research phase
"Use Context7 to research:
1. Event sourcing patterns
2. CQRS implementation strategies
3. Event store databases"
// Use database MCP for event store
"Connect to PostgreSQL MCP to design event store schema"
// Event sourcing implementation:
"Implement event sourcing with:
Plan:
1. Design event schema
2. Implement event store
3. Create projections
4. Add replay capability
Todo:
- [ ] Event store design with versioning
- [ ] Event replay capability
- [ ] Snapshots for performance
- [ ] CQRS pattern implementation
- [ ] Projection updates with eventual consistency"
// Serverless setup:
"Create serverless functions for:
- AWS Lambda handlers
- Cold start optimization
- Shared layers
- Environment configuration
- Local development setup"