.cursorrules in survivorforge/cursor-rules runs 1,152 words across 14 headings.
🤖 Curated collection of .cursorrules files for Cursor IDE — boost your AI coding with framework-specific rules for React, Next.js, Python, Node.js, and more
Covers
11 of the 20 section tags
In the order a file is read inHeadings
14 headings, in the order the file writes them
01Node.js with Express and TypeScript — Cursor Rules
02Code Style
03Express Architecture
04Middleware
05Request Validation
06Error Handling
07TypeScript Patterns
08Database (Prisma or TypeORM)
09Authentication and Authorization
10Logging
11Testing
12File Structure
13Security
14Performance
Commands
1 commands this file writes down
Extracted from the file, verbatimnpm audit
The file
rules/nodejs-express/.cursorrules
160 lines1# 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
The rest of the repository
survivorforge/cursor-rules ships 20 other instruction files
rules/api-design-rest/.cursorrulesrules/database-sql/.cursorrulesrules/docker-devops/.cursorrulesrules/go-gin/.cursorrulesrules/nextjs-14-app-router/.cursorrulesrules/nextjs-typescript/.cursorrulesrules/python-django/.cursorrulesrules/python-modern/.cursorrulesrules/react-typescript/.cursorrulesrules/rust-actix/.cursorrulesrules/rust-production/.cursorrulesrules/tailwind-ui/.cursorrulesrules/tailwindcss/.cursorrulesrules/testing-tdd/.cursorrulesrules/typescript/.cursorrulesrules/vue3-composition/.cursorrulesrules/langchain-ai/.cursorrulesrules/saas-starter/.cursorrulesrules/api-microservices/.cursorrulesrules/mobile-react-native/.cursorrules
This listing
Whoever runs survivorforge/cursor-rules can claim it
This is yours? Claim this config and we will write to you when the measurement moves. The check is one token placed where only you can place it, and there is no account and no password.