Actionable rules for implementing software design patterns with TypeScript, React, Node.js micro-services and cloud-native architecture.
Transform scattered architecture decisions into a proven, automated design pattern framework that scales with your team and codebase.
You know the cycle: start a new feature, copy-paste similar patterns from other parts of the codebase, modify them slightly, and hope they work together. Six months later, you're debugging inconsistent error handling across services, fighting React state management complexity, and explaining to stakeholders why "simple" changes take weeks.
The real cost isn't just technical debt—it's the cognitive overhead of constantly making low-level architectural decisions instead of focusing on business logic. Your team burns cycles debating whether to use a factory or builder pattern while competitors ship features.
These Cursor Rules establish a comprehensive pattern library that automatically guides architecture decisions across your entire TypeScript stack. From React components to microservices, you get consistent, battle-tested implementations that your IDE suggests before you even finish typing.
What you get:
Before: 2-3 hours per review debating architectural approaches and catching inconsistencies After: 15-20 minutes focused on business logic, with patterns pre-validated
Before: 2-3 weeks for new developers to understand your architecture decisions After: 3-5 days with self-documenting, consistent patterns across the codebase
Before: 40% of production issues stem from inconsistent error handling and state management After: 80%+ reduction in architecture-related bugs through automated pattern enforcement
You start typing a new service class, and Cursor immediately suggests the microservice factory pattern:
// Your IDE autocompletes this entire structure
interface PaymentProcessor {
process(payment: PaymentRequest): Promise<Result<PaymentResponse, PaymentError>>
}
export const paymentProcessorFactory = (provider: 'stripe' | 'paypal'): PaymentProcessor => {
// Circuit breaker, retry logic, and observability automatically included
}
The rules ensure every service includes circuit breaker configuration, structured logging, and proper error boundaries—without you having to remember or implement them manually.
Building a complex dashboard component? The rules automatically separate concerns:
// Container (data logic)
const usePaymentDashboard = () => {
const [state, dispatch] = useReducer(paymentReducer, initialState)
// Error boundary and loading states handled automatically
return [state, actions] as const
}
// Presentational (UI only)
const PaymentDashboard = ({ payments, onAction }: PaymentDashboardProps) => {
// Pure component, no side effects
}
No more debating whether state belongs in the component or a custom hook—the patterns are decided and enforced.
Need to coordinate between services? The Saga pattern implementation is ready:
// Automatically includes outbox pattern, idempotency, and correlation IDs
const orderProcessingSaga = createSaga([
paymentStep,
inventoryStep,
shippingStep
], {
compensation: rollbackStrategy,
timeout: 30000
})
Your distributed transactions become reliable and traceable without manual coordination logic.
.cursorrules filetsconfig.json with the recommended settingsThe rules work through three mechanisms:
Intelligent Suggestions: As you type, Cursor recognizes patterns and suggests complete implementations
// Type "factory" and get the full pattern
const userRepositoryFactory = (db: Database): UserRepository => // auto-completed
Automated Validation: Your CI pipeline enforces pattern compliance
# Auto-generated pipeline step
- name: Pattern Validation
run: npm run lint:patterns && npm run test:coverage
Documentation Generation: Every pattern includes auto-generated docs
## Factory Pattern - User Repository
**Intent**: Abstract database implementation details
**When to Use**: Multiple data sources or testing with mocks
**Consequences**: +flexibility, +testability, -complexity for simple cases
As your team grows, the patterns scale with you. New developers don't reinvent architectural wheels—they inherit a proven system that handles cross-cutting concerns automatically. Senior developers focus on business problems instead of explaining why you chose observer over event emitter for the third time this month.
These rules don't just give you textbook implementations—they solve real production challenges:
Stop debating architecture decisions and start shipping features. Your design patterns should work for you, not against you.
Ready to transform your development workflow? Implement these rules today and experience the difference between ad-hoc architecture and systematic design pattern automation.
You are an expert in TypeScript, Node.js, React, Microservices, and Cloud-Native Design Patterns.
Key Principles
- Match the pattern to the problem, not vice-versa. Start from requirements, constraints, scale, and domain events.
- Ensure single responsibility and clear separation of concerns across modules, services, and UI layers.
- Prefer composition over inheritance. De-couple modules through interfaces, events, or dependency injection.
- Keep all public APIs immutable; expose state via functions or read-only properties only.
- Prototype, test, and iterate patterns with real user & business feedback before widespread adoption.
- Automate enforcement via lint, static analysis, and CI gates.
TypeScript
- Use `interface` for contracts; never depend on concrete classes in consumers.
- Enable `strict`, `noImplicitAny`, `exactOptionalPropertyTypes` in `tsconfig`.
- Use `enum` only for closed sets; otherwise prefer string literal unions.
- Express patterns as pure functions or factory functions unless mutable state is essential.
- File layout: `index.ts` (public interface) ➔ `impl/` (concrete classes) ➔ `__tests__/`.
- Example – Factory:
```ts
interface Transport { move(): void }
class Car implements Transport { move() { console.log('driving') } }
class Bike implements Transport { move() { console.log('pedaling') } }
export const transportFactory = (t: 'car'|'bike'): Transport =>
t === 'car' ? new Car() : new Bike();
```
Error Handling & Validation
- Fail fast: validate constructor/factory arguments up front; throw typed `DomainError` with code & context.
- Provide centralized error boundary (React) and global error middleware (Express/Fastify) that log, mask PII, and map to HTTP status.
- For async flows, wrap promises in a `Result<T,E>` monad or use `async/await` + `try/catch` with typed errors.
- Security first: sanitize inputs, enforce least privilege, and log all authz failures.
React (UI Framework)
- Use Presentational vs. Container split: UI components receive props only; containers own data fetching.
- Custom Hooks replace most Higher-Order Components; prefix with `use` and return `[state, actions]`.
- State hierarchy: component → context → Redux/ Zustand; never mix patterns in the same feature.
- Error boundary around route level; show fallback UI and send error to monitoring service.
- Example – Strategy Pattern via Hook:
```ts
type SortStrategy<T> = (a:T,b:T)=>number;
export const useSorter = <T>(strategy: SortStrategy<T>) =>
(list: T[]) => [...list].sort(strategy);
```
Microservices Architecture
- Gateway Pattern: one entrypoint handles auth, rate-limit, and request aggregation.
- Circuit Breaker (e.g., `opossum`): open after 50% failures/10 requests, half-open after 30 s.
- Service Discovery via DNS/Raft (Consul). Do not hard-code hostnames.
- Saga/Outbox Pattern for distributed transactions—use message bus or Kafka and idempotent handlers.
- Observability: mandatory structured logs, traces, and metrics label `service`, `version`, `correlationId`.
Cloud Patterns
- Cache-Aside (Redis) for read-heavy resources: TTL ≤ 1 h, use `Cache-Control` in HTTP response.
- Retry with exponential back-off (100 ms × 2^n, max 5 tries) and jitter.
- Backend-for-Frontend: separate BFF per UI client; contain view-specific aggregation and transformation logic.
Additional Sections
Testing
- TDD where viable; minimum 80 % statement coverage.
- Use Jest + ts-jest. Mock external services with contract tests (Pact) rather than generic stubs.
- Use property-based tests for algorithms (e.g., QuickCheck style with `fast-check`).
Performance
- Profile before optimizing; capture baseline metrics in CI.
- Prefer lazy loading (`React.lazy`) and code-splitting per route.
- Use worker pools (`node:worker_threads`) for CPU-bound tasks.
- Guard shared caches with fine-grained keys to avoid stampeding.
Security
- Mandatory SCA (OWASP Dependency-Check) on each merge.
- Lint for insecure patterns (`no-eval`, open redirects, SQL injection string concatenation).
- Secrets in ENV or vault only; never commit to VCS.
- Enforce HTTPS/TLS 1.3 everywhere, HSTS 1 year.
Tooling & Automation
- CI: lint → type-check → test → build → deploy; block merge if any stage fails.
- Auto-generate docs (`TypeDoc`, `Storybook` for components) and publish to shared portal.
- Static analysis (`SonarQube`) for code smells; coverage gate set to 80 %.
Documentation
- Each pattern file/folder contains `README.md` with: intent, UML, consequences, references.
- Use ADR (Architecture Decision Record) format for pattern selection decisions.
Pitfalls & Edge Cases
- Singleton in serverless ➔ may instantiate per invocation; store state externally if required.
- Observer with unbounded subscribers ➔ memory leak; add `unsubscribe` & auto-prune.
- Command Pattern with long-running tasks ➔ wrap in queue; never block request/response thread.