cursor-handbook / backend
Cursor rule31 starsChanged 3 months agoMITView on GitHub
Backend handler/controller pattern rules and flow. Apply when editing handlers or API routes.
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository30 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/architecture/core-principles.mdcCursor rule
- .cursor/rules/architecture/dependency-management.mdcCursor rule
- .cursor/rules/architecture/token-efficiency.mdcCursor rule
- .cursor/rules/backend/api-design.mdcCursor rule
- .cursor/rules/backend/code-organization.mdcCursor rule
- .cursor/rules/backend/error-handling.mdcCursor rule
- .cursor/rules/backend/nodejs.mdcCursor rule
- .cursor/rules/backend/typescript.mdcCursor rule
- .cursor/rules/cloud/containerization.mdcCursor rule
- .cursor/rules/cloud/infrastructure.mdcCursor rule
- .cursor/rules/cloud/serverless.mdcCursor rule
- .cursor/rules/database/migration-rules.mdcCursor rule
- .cursor/rules/database/query-patterns.mdcCursor rule
- .cursor/rules/database/schema-design.mdcCursor rule
- .cursor/rules/devops/ci-cd.mdcCursor rule
- .cursor/rules/devops/documentation-standards.mdcCursor rule
- .cursor/rules/devops/monitoring.mdcCursor rule
- .cursor/rules/frontend/accessibility.mdcCursor rule
- .cursor/rules/frontend/component-patterns.mdcCursor rule
- .cursor/rules/frontend/performance.mdcCursor rule
- .cursor/rules/frontend/state-management.mdcCursor rule
- .cursor/rules/main-rules.mdcCursor rule
- .cursor/rules/security/guardrails.mdcCursor rule
- .cursor/rules/security/secrets-rules.mdcCursor rule
- .cursor/rules/security/security-compliance.mdcCursor rule
- .cursor/rules/testing/integration-testing.mdcCursor rule
- .cursor/rules/testing/mock-patterns.mdcCursor rule
- .cursor/rules/testing/testing-standards.mdcCursor rule
The file
We split this handler-patterns.mdc into the rules it gives an agent
11 rules. About 0 are common, 10 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 10
Every API handler MUST follow this {{CONFIG.patterns.handlerFlowSteps}}-step flow:
- Distinctive: line 85
Use dependency injection for external services
- Distinctive: line 87
Always pass correlationId through the entire flow
- Distinctive: line 90
Don't put business logic in validate-request — validation only
- Distinctive: line 91
Don't skip validate-business — always check entity state before operation
- Distinctive: line 92
Don't call DB/services from pre-processing — only transform data
- Distinctive: line 93
Don't await post-operation in handler — fire-and-forget or queue
- Distinctive: line 94
Don't return raw result — always use formatResponse envelope
- Distinctive: line 106
Idempotency for POST: Use idempotency key header.
- Distinctive: line 108
Concurrent updates: Use optimistic locking (version field) or last-write-wins with audit
- Very specific: line 111
Use @create-handler skill when creating new handlers
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: "Backend handler/controller pattern rules and flow. Apply when editing handlers or API routes."
alwaysApply: false
globs: "**/handlers/**/*.ts,**/api/**/*.ts,**/*.handler.ts,**/*.controller.ts"
---
# Handler Pattern Rules
## Handler Flow
Every API handler MUST follow this {{CONFIG.patterns.handlerFlowSteps}}-step flow:
### Step-by-Step Flow
1. **Validate Request** — Schema validation, type checking, required fields
2. **Validate Business** — Business rule validation, entity state checks
3. **Pre-Processing** — Data transformation, enrichment, defaults
4. **Operation** — Core business logic execution
5. **Post-Operation** — Side effects (events, notifications, cache invalidation)
6. **Response** — Format and return response
7. **Exit** — Cleanup, logging
### Handler Directory Structure
```
{{CONFIG.paths.handlerBasePath}}/{entity}/{operation}/
├── {{CONFIG.fileNames.handlerEntry}} # Handler entry point
├── {{CONFIG.folderNames.logic}}/
│ ├── validate-request.ts # Step 1
│ ├── validate-business.ts # Step 2
│ ├── pre-processing.ts # Step 3
│ ├── operation.ts # Step 4
│ ├── post-operation.ts # Step 5
│ └── response.ts # Step 6
└── {{CONFIG.folderNames.schemas}}/
├── {{CONFIG.fileNames.requestSchema}} # Request validation schema
└── {{CONFIG.fileNames.responseSchema}} # Response format schema
```
### Handler Entry Point Template
```{{CONFIG.techStack.language}}
import { Request, Response, NextFunction } from '{{CONFIG.techStack.framework}}';
import { validateRequest } from './logic/validate-request';
import { validateBusiness } from './logic/validate-business';
import { preProcessing } from './logic/pre-processing';
import { operation } from './logic/operation';
import { postOperation } from './logic/post-operation';
import { formatResponse } from './logic/response';
import { logger } from '{{CONFIG.paths.commonPath}}/logger';
export async function handler(req: Request, res: Response, next: NextFunction) {
const correlationId = req.headers['x-correlation-id'] as string;
const log = logger.child({ correlationId, operation: 'handler-name' });
try {
// Step 1: Validate Request
const validatedInput = await validateRequest(req.body);
// Step 2: Validate Business Rules
await validateBusiness(validatedInput);
// Step 3: Pre-Processing
const processedData = await preProcessing(validatedInput);
// Step 4: Core Operation
const result = await operation(processedData);
// Step 5: Post-Operation (async side effects)
await postOperation(result);
// Step 6: Response
const response = formatResponse(result);
// Step 7: Exit
log.info({ status: 'success' }, 'Handler completed');
return res.status(200).json(response);
} catch (error) {
log.error({ error: error.message }, 'Handler failed');
next(error);
}
}
```
## Rules
- Each logic step MUST be a pure function (no side effects except in post-operation)
- Each logic file should have a single default export
- Schemas MUST be JSON Schema format for request/response validation
- Use dependency injection for external services
- Handler functions MUST be async
- Always pass correlationId through the entire flow
## Anti-patterns
- Don't put business logic in validate-request — validation only
- Don't skip validate-business — always check entity state before operation
- Don't call DB/services from pre-processing — only transform data
- Don't await post-operation in handler — fire-and-forget or queue
- Don't return raw result — always use formatResponse envelope
## Examples
```ts
// BAD: correlationId not passed
const result = await operation(processedData);
// GOOD: correlationId in context
const result = await operation({ ...processedData, correlationId });
```
## Edge Cases
- **Idempotency for POST**: Use idempotency key header; check before create
- **Pagination for list**: Return cursor + hasNextPage; never unbounded
- **Concurrent updates**: Use optimistic locking (version field) or last-write-wins with audit
## Related
- Use `@create-handler` skill when creating new handlers
- See `@api-design` for URL structure and response envelope
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

