RuleStack

Configs

Stacks

Compare

Diff

RuleStack

Configs

Stacks

Compare

Diff

Read API

RuleStack

Configs

Stacks

Compare

Diff

Read API

Configs/.cursorrules/survivorforge/cursor-rules

.cursorrules (deprecated)

rules/nodejs-express/.cursorrules
.cursorrules

Quality

92/100

Scores the file, not the repository.

Length

1,152 words

14 headings · 2 code blocks

Repository

16

— · pushed 109 days ago

Last changed

2 days ago

First indexed 2 days ago.
survivorforge/cursor-rules/rules/nodejs-express/.cursorrulesRawGitHub
1# Node.js with Express and TypeScript — Cursor Rules
2 
3You are an expert Node.js developer building REST APIs with Express and TypeScript, following production-grade patterns.
4 
5## Code Style
6 
7- Use TypeScript strict mode (`"strict": true` in tsconfig). Never use `any` — prefer `unknown` with type narrowing.
8- Use `const` by default, `let` only when reassignment is needed. Never use `var`.
9- Use `camelCase` for variables and functions, `PascalCase` for classes and interfaces, `UPPER_SNAKE_CASE` for constants.
10- Use `interface` for object shapes that can be extended. Use `type` for unions, intersections, and utility types.
11- Prefer `async/await` over `.then()` chains. Never use callbacks except for legacy library compatibility.
12- Use named exports over default exports for better refactoring support and tree-shaking.
13- Import order: Node.js built-ins, third-party packages, project modules, types. Separate groups with blank lines.
14- Use ESM (`import/export`) over CommonJS (`require/module.exports`). Set `"type": "module"` in package.json.
15- Line length: 100 characters. Use Prettier for formatting, ESLint with `@typescript-eslint` for linting.
16- File naming: kebab-case for files (`user-controller.ts`), PascalCase for classes in code.
17 
18## Express Architecture
19 
20- Use a layered architecture: Routes -> Controllers -> Services -> Repositories.
21- Routes define HTTP endpoints and attach middleware. Controllers handle request/response. Services contain business logic. Repositories handle data access.
22- Controllers should only extract data from the request, call services, and format the response. No business logic in controllers.
23- Services should be framework-agnostic — they should not import Express types or access `req`/`res`.
24- Use Express Router for modular route definitions. One router file per resource.
25- Register global middleware in the app setup. Register route-specific middleware in the router.
26 
27## Middleware
28 
29- Create typed middleware with proper Express types:
30 `(req: Request, res: Response, next: NextFunction) => void`.
31- Use middleware for cross-cutting concerns: logging, auth, validation, rate limiting, CORS.
32- Error-handling middleware has four parameters: `(err: Error, req: Request, res: Response, next: NextFunction)`.
33- Register error-handling middleware last, after all routes.
34- Create an `AsyncHandler` wrapper to catch async errors: wrap route handlers so rejected promises call `next(err)`.
35 
36## Request Validation
37 
38- Validate all request input (body, params, query) before processing. Use Zod for schema validation.
39- Create validation middleware that validates against a Zod schema and attaches typed data to the request.
40- Define request schemas alongside the route: `const createUserSchema = z.object({ body: z.object({ ... }) })`.
41- Return 400 with detailed validation errors. Format: `{ "errors": [{ "field": "email", "message": "Invalid email" }] }`.
42- Validate path params and query params too, not just request body.
43 
44## Error Handling
45 
46- Create a custom `AppError` class extending `Error` with `statusCode`, `code`, and `isOperational` properties.
47- Use specific error classes: `NotFoundError`, `ValidationError`, `UnauthorizedError`, `ForbiddenError`.
48- Throw errors in services and repositories. Catch them in the global error handler middleware.
49- Global error handler: log the error, send appropriate status code and message, hide internal details in production.
50- Use `process.on('unhandledRejection')` and `process.on('uncaughtException')` for safety, but fix the root cause.
51- Never send stack traces in production responses. Include a `requestId` for support correlation.
52 
53## TypeScript Patterns
54 
55- Extend the Express `Request` type for custom properties (e.g., `req.user`):
56```typescript
57 declare global {
58 namespace Express {
59 interface Request {
60 user?: AuthenticatedUser;
61 requestId: string;
62 }
63 }
64 }
65```
66- Use generic service functions: `async function findById<T>(model: Model<T>, id: string): Promise<T>`.
67- Define response types: `interface ApiResponse<T> { success: boolean; data: T; message?: string }`.
68- Use `Zod` with `z.infer<typeof schema>` for deriving TypeScript types from validation schemas.
69 
70## Database (Prisma or TypeORM)
71 
72- Use Prisma as the default ORM for new projects. Use TypeORM if the project already uses it.
73- Define models in `schema.prisma`. Use `@map` and `@@map` for custom table/column names.
74- Use transactions for operations that must be atomic: `prisma.$transaction([...])`.
75- Create a shared Prisma client instance. Do not instantiate per request.
76- Use repository pattern to encapsulate database queries. One repository per model.
77- Use pagination for all list queries. Support `page`/`limit` or `cursor`-based pagination.
78- Use `select` and `include` to control which fields are returned. Avoid fetching unnecessary data.
79 
80## Authentication and Authorization
81 
82- Use JWT for stateless auth. Use `jsonwebtoken` for token creation and verification.
83- Store tokens in httpOnly, secure, sameSite cookies for browser clients. Use Authorization header for API clients.
84- Create an `authMiddleware` that verifies the JWT and attaches the user to the request.
85- Implement role-based access control (RBAC) with a `requireRole('admin')` middleware.
86- Hash passwords with `bcrypt` (minimum 12 salt rounds). Never store plaintext passwords.
87- Implement refresh token rotation for long-lived sessions.
88 
89## Logging
90 
91- Use a structured logger (`pino` or `winston`). Never use `console.log` in production code.
92- Log at appropriate levels: `error` for failures, `warn` for degraded service, `info` for significant events, `debug` for development.
93- Include `requestId` in all log entries for request tracing.
94- Log request method, path, status code, and duration for every request (middleware).
95- Never log sensitive data: passwords, tokens, personal information, credit card numbers.
96 
97## Testing
98 
99- Use Vitest or Jest for unit and integration tests. Use Supertest for HTTP endpoint tests.
100- Unit test services and utilities in isolation. Mock external dependencies.
101- Integration test endpoints with Supertest against a running app instance (use test database).
102- Structure: `*.test.ts` files colocated with source, or a `__tests__/` directory.
103- Use factories or fixtures for creating test data. Clean up after each test.
104- Test error cases: invalid input, missing auth, forbidden access, not found resources.
105 
106## File Structure
107 
108```
109src/
110 app.ts — Express app setup, middleware registration
111 server.ts — HTTP server startup, graceful shutdown
112 config/
113 index.ts — Environment config with Zod validation
114 database.ts — Database connection setup
115 middleware/
116 auth.ts — Authentication middleware
117 validate.ts — Request validation middleware
118 error-handler.ts — Global error handler
119 request-logger.ts — Request logging
120 modules/
121 users/
122 user.controller.ts
123 user.service.ts
124 user.repository.ts
125 user.routes.ts
126 user.schema.ts — Zod validation schemas
127 user.types.ts — TypeScript interfaces
128 items/
129 item.controller.ts
130 item.service.ts
131 item.repository.ts
132 item.routes.ts
133 lib/
134 errors.ts — Custom error classes
135 logger.ts — Logger instance
136 prisma.ts — Prisma client singleton
137 types/
138 express.d.ts — Express type extensions
139```
140 
141## Security
142 
143- Use `helmet` middleware for security headers.
144- Use `cors` middleware with explicit allowed origins. Never use `origin: '*'` in production.
145- Rate limit all endpoints with `express-rate-limit`. Tighter limits on auth endpoints.
146- Sanitize user input. Use parameterized queries (Prisma handles this). Never concatenate input into queries.
147- Validate `Content-Type` header. Reject unexpected content types.
148- Implement request size limits with `express.json({ limit: '10kb' })`.
149- Use `hpp` (HTTP Parameter Pollution) protection middleware.
150- Keep all dependencies updated. Run `npm audit` regularly.
151 
152## Performance
153 
154- Use `compression` middleware for response compression.
155- Implement caching with Redis for frequently accessed data. Use `ioredis` for Redis client.
156- Use connection pooling for database connections (Prisma handles this by default).
157- Implement graceful shutdown: stop accepting new connections, finish in-flight requests, close database connections.
158- Use `cluster` module or PM2 for multi-process deployment on multi-core machines.
159- Set appropriate timeouts on HTTP requests to external services.
160 

Commands it names

  • npm audit

Sections

  • Node.js with Express and TypeScript — Cursor Rules
  • Code Style
  • Express Architecture
  • Middleware
  • Request Validation
  • Error Handling
  • TypeScript Patterns
  • Database (Prisma or TypeORM)
  • Authentication and Authorization
  • Logging
  • Testing
  • File Structure
  • Security
  • Performance

What it covers

testlint-formatcode-stylearchitecturetypestesting-strategysecuritydatabaseperformancedo-notagent-behaviour

Format

.cursorrules

Cursor's original single-file format, superseded by .cursor/rules/*.mdc. Tracked here precisely because it is dead: how much of the ecosystem is still shipping a deprecated file is a measurable answer, and a large share of the "best cursor rules" pages on the web still teach this format.

What the corpus says about it

Repository

Owner
survivorforge
Language
—
License
—
Archived
no

All configs in this repo

Also in survivorforge/cursor-rules

Diff this repo’s formats

One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?

The other instruction files in this repository
RepositoryFormatStackCoversScoreChanged
survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 16.cursorrulesunclassifiedteststylearchdeployment+281/1002 days ago
survivorforge/cursor-rulesrules/api-design-rest/.cursorrules · 16.cursorrulesunclassifiedlint-formatstylesecurityapi+369/1002 days ago
survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 16.cursorrulesnodejavascriptbuildteststylearch+592/1002 days ago
survivorforge/cursor-rulesrules/aws-serverless/.cursorrules · 16.cursorrulesunclassifiedteststylearchtypes+673/1002 days ago
survivorforge/cursor-rulesrules/chrome-extension/.cursorrules · 16.cursorrulesunclassifiedteststylearchtesting-strategy+481/1002 days ago
survivorforge/cursor-rulesrules/clean-code/.cursorrules · 16.cursorrulesunclassifiedstyledo-notagent-behaviourdocs57/1002 days ago
survivorforge/cursor-rulesrules/database-sql/.cursorrules · 16.cursorrulesunclassifiedstyletypessecuritydatabase+365/1002 days ago
survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 16.cursorrulesnodejavascriptsetupbuildteststyle+493/1002 days ago
survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 16.cursorrulesnodejavascriptbuildteststylesecurity+393/1002 days ago
survivorforge/cursor-rulesrules/django-rest/.cursorrules · 16.cursorrulesunclassifiedbuildteststylearch+584/1002 days ago
survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 16.cursorrulesunclassifiedsetupteststylearch+685/1002 days ago
survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 16.cursorrulesunclassifiedteststylearchtypes+589/1002 days ago
survivorforge/cursor-rulesrules/fullstack-nextjs-prisma/.cursorrules · 16.cursorrulesunclassifiedteststylearchtypes+796/1002 days ago
survivorforge/cursor-rulesrules/go-gin/.cursorrules · 16.cursorrulesunclassifiedtestlint-formatstylearch+584/1002 days ago
survivorforge/cursor-rulesrules/go-production/.cursorrules · 16.cursorrulesunclassifiedteststylearchtesting-strategy+389/1002 days ago
survivorforge/cursor-rulesrules/golang-api/.cursorrules · 16.cursorrulesunclassifiedbuildteststylearch+684/1002 days ago
survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 16.cursorrulesunclassifiedtestlint-formatstylearch+484/1002 days ago
survivorforge/cursor-rulesrules/mcp-server/.cursorrules · 16.cursorrulesunclassifiedtestlint-formatstylearch+768/1002 days ago
survivorforge/cursor-rulesrules/mern-stack/.cursorrules · 16.cursorrulesunclassifiedsetupteststylearch+681/1002 days ago
survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 16.cursorrulesunclassifiedteststylearchtypes+789/1002 days ago
Diff against rules/ai-ml-python/.cursorrules Diff against rules/api-design-rest/.cursorrules Diff against rules/api-microservices/.cursorrules Diff against rules/aws-serverless/.cursorrules Diff against rules/chrome-extension/.cursorrules Diff against rules/clean-code/.cursorrules Diff against rules/database-sql/.cursorrules Diff against rules/devops-docker/.cursorrules Diff against rules/devops-infrastructure/.cursorrules Diff against rules/django-rest/.cursorrules Diff against rules/docker-devops/.cursorrules Diff against rules/flutter-dart/.cursorrules Diff against rules/fullstack-nextjs-prisma/.cursorrules Diff against rules/go-gin/.cursorrules Diff against rules/go-production/.cursorrules Diff against rules/golang-api/.cursorrules Diff against rules/langchain-ai/.cursorrules Diff against rules/mcp-server/.cursorrules Diff against rules/mern-stack/.cursorrules Diff against rules/mobile-react-native/.cursorrules
RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack