{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cursor-rule-back-end",
  "title": "Cursor Rule: Back End",
  "description": "Cursor rule file for back-end development guidelines.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/optics/cursor/rules/back-end.mdc",
      "content": "---\ndescription: Rules for back-end development\nglobs: *.js, *.jsx, *.ts, *.tsx\nalwaysApply: false\n---\n# Backend Development Rules\n\n## Languages and Frameworks\n\nExpert in Node.js, Express, Next.js API Routes, Server Actions, Route Handlers, Fastify, Prisma, Drizzle.\n\nUse JavaScript by default. Use TypeScript when explicitly requested or when project requires it.\n\nFor monolithic Next.js apps, prefer Server Actions over API Routes when possible for better type safety and reduced boilerplate.\n\n## Next.js Backend Patterns\n\nServer Actions are the preferred way to handle mutations in Next.js 16:\n```javascript\n'use server'\nexport async function createUser(formData) {\n  // Validate, process, return result\n}\n```\n\nUse Route Handlers (app/api) for:\n- External API consumption\n- Webhooks\n- Non-form mutations\n- Integrations with third-party services\n\nServer Actions provide automatic serialization, type safety, and progressive enhancement.\n\nUse \"use cache\" directive for caching expensive computations or data fetching.\n\nAlways revalidate or update cache after mutations using updateTag() or revalidateTag().\n\n## Error Handling\n\nWrap all async operations in try-catch blocks. Never let errors crash the server.\n\nReturn structured error responses with appropriate HTTP status codes and messages.\n\nCreate custom error classes for different error types (ValidationError, AuthError, NotFoundError).\n\nGood:\n```javascript\ntry {\n  const user = await db.user.findUnique({ where: { id } })\n  if (!user) throw new NotFoundError('User not found')\n  return user\n} catch (error) {\n  if (error instanceof NotFoundError) {\n    return { error: error.message, status: 404 }\n  }\n  return { error: 'Internal server error', status: 500 }\n}\n```\n\nLog errors properly with context (user ID, request ID, timestamp) but never expose stack traces to clients.\n\n## Input Validation\n\nValidate all incoming data at the entry point. Never trust client input.\n\nUse validation libraries like Zod or Yup for schema validation:\n```javascript\nconst userSchema = z.object({\n  email: z.string().email(),\n  age: z.number().min(18)\n})\n\nconst result = userSchema.safeParse(data)\nif (!result.success) {\n  return { error: result.error.flatten(), status: 400 }\n}\n```\n\nValidate types, formats, lengths, and business rules before processing.\n\nSanitize HTML and SQL inputs to prevent injection attacks.\n\nReturn clear validation errors that help clients fix issues without exposing system internals.\n\n## Authentication and Authorization\n\nAlways verify authentication before accessing protected resources.\n\nImplement authorization checks at the business logic level, not just at the route level.\n\nUse JWT tokens, session cookies, or OAuth depending on requirements.\n\nIn Next.js, use middleware or Server Actions for auth checks:\n```javascript\nimport { auth } from '@/lib/auth'\n\nexport async function deletePost(postId) {\n  'use server'\n  const session = await auth()\n  if (!session) throw new AuthError('Unauthorized')\n  // Proceed with deletion\n}\n```\n\nNever expose sensitive data in responses (passwords, internal IDs, tokens).\n\nHash passwords with bcrypt or Argon2, never store plain text.\n\nImplement rate limiting for authentication endpoints to prevent brute force attacks.\n\n## Security Best Practices\n\nSanitize all user inputs to prevent XSS, SQL injection, and command injection.\n\nUse parameterized queries or ORMs to prevent SQL injection.\n\nImplement CSRF protection for state-changing operations.\n\nSet security headers (Content-Security-Policy, X-Frame-Options, X-Content-Type-Options).\n\nUse HTTPS in production. Redirect HTTP to HTTPS.\n\nConfigure CORS properly. Whitelist specific origins, avoid using wildcards in production.\n\nImplement rate limiting to prevent abuse and DDoS attacks.\n\nKeep dependencies updated. Regularly audit for vulnerabilities with npm audit or Snyk.\n\nNever commit secrets, API keys, or credentials to version control. Use environment variables.\n\nDisable unnecessary HTTP headers that expose technology stack (X-Powered-By).\n\n## Logging and Monitoring\n\nUse structured logging libraries (Winston, Pino) instead of console.log.\n\nLog levels: error, warn, info, debug. Use appropriately.\n\nInclude context in logs: request ID, user ID, timestamp, relevant data.\n\nNever log sensitive information (passwords, tokens, credit cards, PII).\n\nGood:\n```javascript\nlogger.info('User created', { \n  userId: user.id, \n  requestId: req.id,\n  timestamp: new Date().toISOString()\n})\n```\n\nImplement centralized error logging and monitoring (Sentry, LogRocket, Datadog).\n\nTrack key metrics: response times, error rates, throughput.\n\n## HTTP Status Codes\n\nUse status codes correctly and consistently:\n\n- 200 OK: Successful GET, PUT, PATCH\n- 201 Created: Successful POST that creates a resource\n- 204 No Content: Successful DELETE\n- 400 Bad Request: Validation errors, malformed requests\n- 401 Unauthorized: Missing or invalid authentication\n- 403 Forbidden: Authenticated but not authorized\n- 404 Not Found: Resource doesn't exist\n- 409 Conflict: Resource conflict (duplicate email, version mismatch)\n- 422 Unprocessable Entity: Valid syntax but semantic errors\n- 429 Too Many Requests: Rate limit exceeded\n- 500 Internal Server Error: Unexpected server errors\n- 503 Service Unavailable: Temporary unavailability\n\n## Response Structure\n\nReturn consistent response structures across all endpoints.\n\nGood:\n```javascript\n// Success\n{ data: { user: {...} }, success: true }\n\n// Error\n{ error: 'User not found', success: false }\n\n// Validation error\n{ error: 'Validation failed', errors: { email: ['Invalid format'] }, success: false }\n```\n\nInclude pagination metadata for list endpoints:\n```javascript\n{ \n  data: [...], \n  pagination: { page: 1, limit: 20, total: 100, hasMore: true }\n}\n```\n\n## Code Structure and Organization\n\nOrganize code by feature or domain, not by technical role:\n```\n/features\n  /users\n    user.service.js\n    user.controller.js\n    user.validation.js\n  /posts\n    post.service.js\n    post.controller.js\n```\n\nSeparate concerns clearly:\n- Routes: Define endpoints and basic request handling\n- Controllers: Handle HTTP specifics (request/response)\n- Services: Contain business logic\n- Repositories/DAL: Database access layer\n- Middleware: Cross-cutting concerns (auth, logging, validation)\n\nKeep controllers thin. Move business logic to services.\n\nGood:\n```javascript\n// Controller\nexport async function createUser(req, res) {\n  const result = await userService.create(req.body)\n  return res.status(201).json(result)\n}\n\n// Service\nexport async function create(userData) {\n  // Business logic here\n  return await db.user.create({ data: userData })\n}\n```\n\n## Database Best Practices\n\nUse an ORM or query builder (Prisma, Drizzle, Knex) for type safety and migrations.\n\nAlways use transactions for operations that modify multiple records.\n\nImplement database-level constraints (unique, foreign keys, not null).\n\nIndex frequently queried columns for better performance.\n\nUse connection pooling to manage database connections efficiently.\n\nAvoid N+1 queries. Use eager loading or batch queries.\n\nValidate data before database operations to catch errors early.\n\n## API Design\n\nUse RESTful conventions when appropriate:\n- GET /users - List users\n- GET /users/:id - Get specific user\n- POST /users - Create user\n- PUT/PATCH /users/:id - Update user\n- DELETE /users/:id - Delete user\n\nUse plural nouns for resources (users, posts, orders).\n\nVersion APIs when breaking changes are needed (/api/v1/, /api/v2/).\n\nKeep endpoints predictable and consistent.\n\nReturn appropriate resource representations after mutations (created/updated resource).\n\n## Environment Configuration\n\nUse environment variables for configuration. Never hardcode credentials or URLs.\n\nValidate required environment variables at startup:\n```javascript\nconst requiredEnvVars = ['DATABASE_URL', 'JWT_SECRET']\nrequiredEnvVars.forEach(key => {\n  if (!process.env[key]) {\n    throw new Error(`Missing required environment variable: ${key}`)\n  }\n})\n```\n\nUse different configurations for development, staging, and production.\n\nProvide sensible defaults for non-sensitive configuration.\n\n## Testing\n\nWrite unit tests for business logic in services.\n\nWrite integration tests for API endpoints.\n\nTest error cases, not just happy paths.\n\nMock external dependencies in tests.\n\nUse descriptive test names that explain what is being tested.\n\n## Performance\n\nImplement caching strategies where appropriate (Redis, in-memory, CDN).\n\nUse async/await consistently. Avoid blocking operations.\n\nImplement pagination for large datasets. Never return unbounded lists.\n\nUse database indexes on frequently queried fields.\n\nConsider background jobs for heavy operations (emails, image processing).\n\nMonitor and optimize slow queries and endpoints.\n\n## Documentation\n\nDocument all API endpoints with expected inputs and outputs.\n\nInclude example requests and responses.\n\nDocument error responses and status codes.\n\nKeep documentation updated when endpoints change.\n\nUse JSDoc comments for complex functions.\n\n## Code Quality Principles\n\nFollow KISS: Keep solutions simple and straightforward.\n\nFollow DRY: Don't repeat yourself. Extract common logic.\n\nKeep functions focused on a single responsibility.\n\nUse pure functions when possible (same input always produces same output, no side effects).\n\nName functions clearly based on what they do (createUser, validateEmail, sendNotification).\n\nKeep functions small. If over 30-40 lines, consider refactoring.\n\n## Deployment Considerations\n\nUse health check endpoints for monitoring:\n```javascript\napp.get('/health', (req, res) => {\n  res.json({ status: 'ok', timestamp: new Date() })\n})\n```\n\nImplement graceful shutdown to finish pending requests before stopping.\n\nUse process managers (PM2) or container orchestration (Docker, Kubernetes).\n\nSet up proper logging and monitoring in production.\n\nConfigure appropriate timeouts for requests and connections.",
      "type": "registry:file",
      "target": "~/.cursor/rules/back-end.mdc"
    }
  ],
  "type": "registry:file"
}