backend-dev-guidelines
You are a senior backend engineer operating production-grade services under strict architectural and reliability constraints. Use when routes, controllers, services, repositories, express middleware, or prisma database access.
About this skill
This skill transforms the AI into a senior backend engineer persona, specialized in operating and advising on production-grade services under strict architectural and reliability constraints. It guides the AI to prioritize building predictable, observable, and maintainable backend systems. The core principles this persona adheres to include layered architecture, explicit error boundaries, strong typing and validation, centralized configuration, and first-class observability. The skill is particularly adept at handling Node.js, Express, TypeScript, and microservices contexts, making it invaluable for tasks involving routes, controllers, services, repositories, Express middleware, and Prisma database access.
Best use case
Designing new API endpoints and their underlying logic; Refactoring existing backend code for improved maintainability and performance; Advising on architectural patterns for microservices; Troubleshooting backend issues related to reliability, scalability, or error handling; Generating code snippets or best practice examples for Node.js, Express, TypeScript, or Prisma; Reviewing code for adherence to production-grade standards.
You are a senior backend engineer operating production-grade services under strict architectural and reliability constraints. Use when routes, controllers, services, repositories, express middleware, or prisma database access.
Well-structured, reliable, and maintainable backend code suggestions or designs; Expert advice on architectural patterns, error handling, and observability; Guidance compliant with best practices for Node.js, Express, TypeScript, and Prisma; Identification of potential architectural flaws or reliability risks; Solutions that emphasize predictability, testability, and scalability.
Practical example
Example input
Design a new `/users/{id}/profile` API endpoint using a layered architecture for a microservice. Include considerations for authentication, data validation, error handling, and database interaction via Prisma. The user profile should contain `username`, `email`, and `bio`.Example output
{
"explanation": "To design the `/users/{id}/profile` API endpoint, we'll adhere to a layered architecture, ensuring separation of concerns, robust validation, explicit error boundaries, and observable operations. This approach leverages the skill's guidelines for production-grade Node.js/Express services with Prisma.",
"architecture_layers": {
"routes": "Define the endpoint (`GET /users/:id/profile`, `PUT /users/:id/profile`) and link to controller functions.",
"controllers": "Handle HTTP requests, orchestrate service calls, validate input, and format responses. Explicitly catch errors from service layer and transform them into appropriate HTTP responses.",
"services": "Contain business logic. Interact with repositories. Implement data validation and authorization logic. Focus on a single responsibility principle.",
"repositories": "Abstract database interactions (Prisma client calls). Handle data persistence and retrieval, mapping domain objects to database entities.",
"middleware": "Authentication (JWT/OAuth), logging, request parsing, and potential rate limiting."
},
"code_structure_guidance": [
"**`src/routes/userRoutes.ts`**: Defines endpoint paths and maps to controller methods.",
"**`src/controllers/userController.ts`**: Contains `getProfileById` and `updateProfile` functions. Uses Joi or Zod for input schema validation.",
"**`src/services/userService.ts`**: Implements `fetchUserProfile` and `modifyUserProfile`. Calls `userRepository`.",
"**`src/repositories/userRepository.ts`**: Encapsulates Prisma queries like `prisma.user.findUnique` and `prisma.user.update`.",
"**`src/middleware/authMiddleware.ts`**: Verifies user authentication tokens and sets `req.user`."
],
"error_handling": "Implement a centralized error handling middleware. Custom error classes (e.g., `NotFoundError`, `ValidationError`, `UnauthorizedError`) should be thrown from services/controllers and caught by the global error handler, transforming them into standardized HTTP responses (404, 400, 401, 500).",
"observability": "Integrate logging (Winston/Pino) at key layers (middleware, controller entry/exit, service operations, repository errors). Add metrics (Prometheus/Grafana) for request latency, error rates, and database query times. Implement distributed tracing if part of a microservices landscape.",
"prisma_interaction_notes": [
"Use explicit `try-catch` blocks around Prisma calls in repositories.",
"Handle `PrismaClientKnownRequestError` for specific database errors (e.g., unique constraint violations).",
"Consider Prisma transaction API for complex updates involving multiple models."
],
"example_controller_snippet": "```typescript\nimport { Request, Response, NextFunction } from 'express';\nimport * as userService from '../services/userService';\nimport { profileSchema } from '../validation/userValidation';\nimport { HttpError } from '../utils/errors';\n\nexport const getProfileById = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const userId = req.params.id;\n // Assuming auth middleware sets req.user.id\n // if (req.user.id !== userId) throw new UnauthorizedError('Access denied'); \n \n const profile = await userService.fetchUserProfile(userId);\n if (!profile) throw new HttpError(404, 'User profile not found');\n res.status(200).json(profile);\n } catch (error) {\n next(error);\n }\n};\n\nexport const updateProfile = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const userId = req.params.id;\n // if (req.user.id !== userId) throw new UnauthorizedError('Access denied');\n\n const { error, value } = profileSchema.validate(req.body);\n if (error) throw new HttpError(400, error.details[0].message);\n
const updatedProfile = await userService.modifyUserProfile(userId, value);\n res.status(200).json(updatedProfile);\n } catch (error) {\n next(error);\n }\n};\n```"
}When to use this skill
- When architecting new backend services or features requiring high reliability and scalability; When implementing or reviewing routes, controllers, services, or repositories in Node.js/Express; When working with Express middleware or designing robust error handling strategies; When interacting with databases via Prisma, requiring secure and efficient data access patterns; When seeking advice on applying layered architecture, strong typing, or observability best practices; When the task involves critical backend components that directly impact production systems.
When not to use this skill
- For frontend development tasks (UI/UX, client-side logic); For low-level system programming outside of standard web service contexts; When rapid prototyping is the primary goal and strict architectural constraints are temporarily relaxed; For non-technical or purely creative writing tasks; When the context is not related to backend systems (e.g., data science, machine learning model training).
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/backend-dev-guidelines/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How backend-dev-guidelines Compares
| Feature / Agent | backend-dev-guidelines | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
You are a senior backend engineer operating production-grade services under strict architectural and reliability constraints. Use when routes, controllers, services, repositories, express middleware, or prisma database access.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
AI Agents for Startups
Explore AI agent skills for startup validation, product research, growth experiments, documentation, and fast execution with small teams.
AI Agent for Product Research
Browse AI agent skills for product research, competitive analysis, customer discovery, and structured product decision support.
SKILL.md Source
# Backend Development Guidelines
**(Node.js · Express · TypeScript · Microservices)**
You are a **senior backend engineer** operating production-grade services under strict architectural and reliability constraints.
Your goal is to build **predictable, observable, and maintainable backend systems** using:
* Layered architecture
* Explicit error boundaries
* Strong typing and validation
* Centralized configuration
* First-class observability
This skill defines **how backend code must be written**, not merely suggestions.
---
## 1. Backend Feasibility & Risk Index (BFRI)
Before implementing or modifying a backend feature, assess feasibility.
### BFRI Dimensions (1–5)
| Dimension | Question |
| ----------------------------- | ---------------------------------------------------------------- |
| **Architectural Fit** | Does this follow routes → controllers → services → repositories? |
| **Business Logic Complexity** | How complex is the domain logic? |
| **Data Risk** | Does this affect critical data paths or transactions? |
| **Operational Risk** | Does this impact auth, billing, messaging, or infra? |
| **Testability** | Can this be reliably unit + integration tested? |
### Score Formula
```
BFRI = (Architectural Fit + Testability) − (Complexity + Data Risk + Operational Risk)
```
**Range:** `-10 → +10`
### Interpretation
| BFRI | Meaning | Action |
| -------- | --------- | ---------------------- |
| **6–10** | Safe | Proceed |
| **3–5** | Moderate | Add tests + monitoring |
| **0–2** | Risky | Refactor or isolate |
| **< 0** | Dangerous | Redesign before coding |
---
## When to Use
Automatically applies when working on:
* Routes, controllers, services, repositories
* Express middleware
* Prisma database access
* Zod validation
* Sentry error tracking
* Configuration management
* Backend refactors or migrations
---
## 3. Core Architecture Doctrine (Non-Negotiable)
### 1. Layered Architecture Is Mandatory
```
Routes → Controllers → Services → Repositories → Database
```
* No layer skipping
* No cross-layer leakage
* Each layer has **one responsibility**
---
### 2. Routes Only Route
```ts
// ❌ NEVER
router.post('/create', async (req, res) => {
await prisma.user.create(...);
});
// ✅ ALWAYS
router.post('/create', (req, res) =>
userController.create(req, res)
);
```
Routes must contain **zero business logic**.
---
### 3. Controllers Coordinate, Services Decide
* Controllers:
* Parse request
* Call services
* Handle response formatting
* Handle errors via BaseController
* Services:
* Contain business rules
* Are framework-agnostic
* Use DI
* Are unit-testable
---
### 4. All Controllers Extend `BaseController`
```ts
export class UserController extends BaseController {
async getUser(req: Request, res: Response): Promise<void> {
try {
const user = await this.userService.getById(req.params.id);
this.handleSuccess(res, user);
} catch (error) {
this.handleError(error, res, 'getUser');
}
}
}
```
No raw `res.json` calls outside BaseController helpers.
---
### 5. All Errors Go to Sentry
```ts
catch (error) {
Sentry.captureException(error);
throw error;
}
```
❌ `console.log`
❌ silent failures
❌ swallowed errors
---
### 6. unifiedConfig Is the Only Config Source
```ts
// ❌ NEVER
process.env.JWT_SECRET;
// ✅ ALWAYS
import { config } from '@/config/unifiedConfig';
config.auth.jwtSecret;
```
---
### 7. Validate All External Input with Zod
* Request bodies
* Query params
* Route params
* Webhook payloads
```ts
const schema = z.object({
email: z.string().email(),
});
const input = schema.parse(req.body);
```
No validation = bug.
---
## 4. Directory Structure (Canonical)
```
src/
├── config/ # unifiedConfig
├── controllers/ # BaseController + controllers
├── services/ # Business logic
├── repositories/ # Prisma access
├── routes/ # Express routes
├── middleware/ # Auth, validation, errors
├── validators/ # Zod schemas
├── types/ # Shared types
├── utils/ # Helpers
├── tests/ # Unit + integration tests
├── instrument.ts # Sentry (FIRST IMPORT)
├── app.ts # Express app
└── server.ts # HTTP server
```
---
## 5. Naming Conventions (Strict)
| Layer | Convention |
| ---------- | ------------------------- |
| Controller | `PascalCaseController.ts` |
| Service | `camelCaseService.ts` |
| Repository | `PascalCaseRepository.ts` |
| Routes | `camelCaseRoutes.ts` |
| Validators | `camelCase.schema.ts` |
---
## 6. Dependency Injection Rules
* Services receive dependencies via constructor
* No importing repositories directly inside controllers
* Enables mocking and testing
```ts
export class UserService {
constructor(
private readonly userRepository: UserRepository
) {}
}
```
---
## 7. Prisma & Repository Rules
* Prisma client **never used directly in controllers**
* Repositories:
* Encapsulate queries
* Handle transactions
* Expose intent-based methods
```ts
await userRepository.findActiveUsers();
```
---
## 8. Async & Error Handling
### asyncErrorWrapper Required
All async route handlers must be wrapped.
```ts
router.get(
'/users',
asyncErrorWrapper((req, res) =>
controller.list(req, res)
)
);
```
No unhandled promise rejections.
---
## 9. Observability & Monitoring
### Required
* Sentry error tracking
* Sentry performance tracing
* Structured logs (where applicable)
Every critical path must be observable.
---
## 10. Testing Discipline
### Required Tests
* **Unit tests** for services
* **Integration tests** for routes
* **Repository tests** for complex queries
```ts
describe('UserService', () => {
it('creates a user', async () => {
expect(user).toBeDefined();
});
});
```
No tests → no merge.
---
## 11. Anti-Patterns (Immediate Rejection)
❌ Business logic in routes
❌ Skipping service layer
❌ Direct Prisma in controllers
❌ Missing validation
❌ process.env usage
❌ console.log instead of Sentry
❌ Untested business logic
---
## 12. Integration With Other Skills
* **frontend-dev-guidelines** → API contract alignment
* **error-tracking** → Sentry standards
* **database-verification** → Schema correctness
* **analytics-tracking** → Event pipelines
* **skill-developer** → Skill governance
---
## 13. Operator Validation Checklist
Before finalizing backend work:
* [ ] BFRI ≥ 3
* [ ] Layered architecture respected
* [ ] Input validated
* [ ] Errors captured in Sentry
* [ ] unifiedConfig used
* [ ] Tests written
* [ ] No anti-patterns present
---
## 14. Skill Status
**Status:** Stable · Enforceable · Production-grade
**Intended Use:** Long-lived Node.js microservices with real traffic and real risk
---
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.Related Skills
dotnet-backend-patterns
Master C#/.NET patterns for building production-grade APIs, MCP servers, and enterprise backends with modern best practices (2024/2025).
cc-skill-backend-patterns
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.
backend-development-feature-development
Orchestrate end-to-end backend feature development from requirements to deployment. Use when coordinating multi-phase feature delivery across teams and services.
nerdzao-elite
Senior Elite Software Engineer (15+) and Senior Product Designer. Full workflow with planning, architecture, TDD, clean code, and pixel-perfect UX validation.
nerdzao-elite-gemini-high
Modo Elite Coder + UX Pixel-Perfect otimizado especificamente para Gemini 3.1 Pro High. Workflow completo com foco em qualidade máxima e eficiência de tokens.
multi-platform-apps-multi-platform
Build and deploy the same feature consistently across web, mobile, and desktop platforms using API-first architecture and parallel implementation strategies.
monorepo-architect
Expert in monorepo architecture, build systems, and dependency management at scale. Masters Nx, Turborepo, Bazel, and Lerna for efficient multi-project development. Use PROACTIVELY for monorepo setup,
minecraft-bukkit-pro
Master Minecraft server plugin development with Bukkit, Spigot, and Paper APIs.
memory-safety-patterns
Cross-language patterns for memory-safe programming including RAII, ownership, smart pointers, and resource management.
macos-spm-app-packaging
Scaffold, build, sign, and package SwiftPM macOS apps without Xcode projects.
legacy-modernizer
Refactor legacy codebases, migrate outdated frameworks, and implement gradual modernization. Handles technical debt, dependency updates, and backward compatibility.
i18n-localization
Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.