Backend Development
<!-- uses:
- mention: add--backend-architecture
- mention: add--database-development
- mention: add--frontend-development
- mention: add--security-audit
-->
Skill for backend API implementation following universal architectural principles.
Use for: Routes/Controllers, Services, DTOs, Domain logic, Data access, Error handling
Not for: Frontend (ux-design), Database migrations (database-development), Security (security-audit)
Stack resolution: Project conventions: follow {{addpath:wiki/conventions.md}} → ## Stack Conventions (+ {{addpath:wiki/domains/<area>.md}}); a one-line critical rule may live in AGENTS.md. If absent, apply the agnostic defaults and follow the nearest existing code; never impose tenancy, DI registration or barrels unless the project uses them. Apply these principles using the framework's idiomatic patterns. The AI already knows each framework's syntax — this skill teaches architecture, not framework tutorials.
Reference: Conventions come from the wiki first; AGENTS.md is the fallback for general project standards.
Project Conventions First
Read in this order: {{addpath:wiki/conventions.md}} → ## Stack Conventions (+ the area page under {{addpath:wiki/domains/<area>.md}}), then AGENTS.md ## Architecture Contract / ## Technical Spec for stack facts. In a tiny wiki the same table sits in {{addpath:wiki/index.md}} → ### Stack Conventions. A recorded row wins over the default below. A row that says none (or no, for Tenancy and Barrels) means the project does not use the thing: follow the nearest existing code.
Agnostic defaults, used only when nothing is recorded (the other dev skills link here and do not copy this list):
- Tenancy (row
Tenancy): none. If a feature introduces tenant-scoped data in a project without tenancy, raise it as a planning question. Never add it silently. - DI (row
DI): pass collaborators in (constructor/parameters) for testability. Register in a container only if the project has one. - Barrels (row
Barrels): do not create new ones. If the folder already has one, add the export. - Entity language (row
Entity language): the project's language and the form used by neighbouring entity files. - Validation (row
Validation): validate at the boundary with the project's library. Never add a new library. If there is none, flag it in the plan. - Data access (row
ORM / data access): use a repository and a mapper (e.g.toEntity) only when the project already uses them or persistence naming differs from domain naming. - Layering (row
Layering): follow{{addpath:wiki/architecture.md}}. The default rule is only "keep HTTP/IO out of business logic".
When NOT to Use
- Frontend / UI work — use
ux-designoradd--frontend-developmentinstead - Database migrations or schema design — use
add--database-development - Security audits / threat modeling — use
add--security-audit - Pure scripts, CLIs, or non-API code — these patterns target HTTP API services
- Greenfield architecture decisions — use
add--backend-architectureto choose structure first - Project scaffolding
Clean Architecture
One common layering, given as an example. The project's own layering ({{addpath:wiki/architecture.md}} / row Layering) wins.
domain → application → infrastructure → presentation
| Layer | Allowed deps | Content |
|---|---|---|
| domain | zero | entities, value objects, enums, types, domain errors |
| application | domain only | service interfaces, use cases, DTOs |
| infrastructure | domain, application | repository implementations, external services, config |
| presentation | all | routes/controllers, middleware, error mapping |
Rules:
- Lower layers NEVER import from upper layers
- Domain has ZERO I/O, ZERO framework dependencies — pure business logic
- Application layer defines interfaces (ports) — infrastructure implements them (adapters)
- Presentation layer is the only place aware of HTTP
SOLID Principles
- SRP — Each class/module has one reason to change. Services don't handle HTTP. Repositories don't validate.
- OCP — Extend behavior via new implementations, not modifying existing code. Strategy/plugin patterns.
- LSP — Implementations must be substitutable for their interfaces without breaking behavior.
- ISP — Prefer small, focused interfaces. Don't force consumers to depend on methods they don't use.
- DIP — Services depend on interfaces, not implementations. Inject abstractions, never concrete classes.
RESTful Standards
| Method | Use | Idempotent | Body | Status |
|---|---|---|---|---|
| GET | read | yes | no | 200 |
| POST | create | no | yes | 201 |
| PUT | full update | yes | yes | 200 |
| PATCH | partial | yes | yes | 200 |
| DELETE | remove | yes | no | 204 |
URL rules:
Do:
- Nouns:
/users - Plural:
/accounts - Nested:
/accounts/:id/users - Kebab:
/user-roles - Versioned:
/api/v1
Don't:
- Verbs:
/getUsers - Singular:
/user - Mixed case:
/userRoles
Params:
- Path → resource id
- Query → filter, pagination, sort, search
Status codes:
| Code | Meaning |
|---|---|
| 200 | GET, PUT, PATCH ok |
| 201 | POST created |
| 204 | DELETE ok |
| 400 | validation |
| 401 | no auth |
| 403 | no permission |
| 404 | not found |
| 409 | conflict |
Dependency Injection / IoC
Principles:
- Services receive dependencies via constructor/parameter injection (the default, container or not)
- Depend on interfaces/abstractions, never concrete implementations
- Only when row
DInames a container: register every service, repository and handler in it, and export cross-module dependencies explicitly
Common DI errors (with a container): Unresolved dependency = not registered. Cross-module failure = not exported. Route 404 = module not loaded. Consult framework docs for idiomatic registration.
Naming Conventions
Follow the project's naming. The tables below are examples, not a mandate.
File naming (example, one stack):
| Type | Pattern |
|---|---|
| Controller / Route | kebab.controller.ts or kebab.routes.ts |
| Service | kebab.service.ts |
| Repository | PascalRepository.ts |
| Interface | IPascalRepository.ts |
| Entity | Pascal.ts |
| Enum | PascalCase.ts |
| DTO | PascalDto.ts |
Casing rules:
| Element | Casing |
|---|---|
| Files | kebab-case or PascalCase (follow project convention) |
| Classes | PascalCase |
| Interfaces | I + PascalCase (example; only if the project uses the prefix) |
| DB columns | snake_case |
| Variables | camelCase |
Paths and aliases: Follow the project's existing import aliases and directory structure. Do not invent new aliases — check the project's alias config (e.g. tsconfig.json paths) and existing code.
DTOs
DTO naming:
| Action | Pattern |
|---|---|
| create | Create[Entity]Dto |
| update | Update[Entity]Dto |
| patch | Patch[Entity]Dto |
| response | [Entity]ResponseDto |
| list | [Entity]ListResponseDto |
| query | [Entity]QueryDto |
Rules:
- Input DTOs (
create/update/patch) are SEPARATE from response DTOs - Validation happens at the presentation layer entry point, NEVER in domain
- Use the project's validation library (class-validator, zod, typebox, valibot, joi, etc.)
- Every input field must have validation rules defined
- Response DTOs control what leaves the API — never expose raw entities
Services
- Business logic lives here — NO HTTP concepts (no
req/res, no status codes, no headers) - Receives pure data (DTOs or primitives), returns pure data (entities or response DTOs)
- Depends on repository interfaces, not implementations
- Orchestrates domain logic — does not contain persistence logic
- One service per bounded context / feature area
Repository Pattern
Use a repository (and a mapper such as toEntity) only when the project already uses them or persistence naming differs from domain naming (row ORM / data access). Otherwise follow the project's data-access style.
When used:
- Interface defined in application/domain layer
- Implementation in infrastructure layer
- Services depend on the interface, never the implementation
- Returns domain entities, not raw rows or ORM-specific objects
- All data access goes through repositories — no direct DB calls in services
Error Handling
| Layer | Responsibility |
|---|---|
| domain | Throw domain-specific errors (NotFoundError, BusinessRuleViolationError, ConflictError). No HTTP concepts. |
| application | Let domain errors propagate. Add application-level errors if needed (ValidationError). |
| presentation | Map domain/application errors to HTTP status codes. This is the ONLY layer that knows about HTTP. |
Error mapping:
| Domain | HTTP |
|---|---|
| NotFoundError | 404 |
| ValidationError | 400 |
| UnauthorizedError | 401 |
| ForbiddenError | 403 |
| ConflictError | 409 |
| BusinessRuleViolationError | 422 |
Rule: Services throw domain errors. The presentation layer (middleware, error handler, or framework mechanism) maps them to HTTP responses. Never import HTTP concepts into services.
Module / Feature Structure
Organize code by domain/feature, not by technical role. Each feature module contains its own controllers, services, DTOs, and domain logic. The tree below is one example layout; the project's structure wins.
[feature]/
├── dtos/
│ ├── Create[Feature]Dto.ts
│ ├── Update[Feature]Dto.ts
│ └── [Feature]ResponseDto.ts
├── [feature].controller.ts (or routes.ts)
├── [feature].service.ts
└── [feature].module.ts (or index.ts)
DDD-lite principles:
- Entities encapsulate behavior (methods, not just data bags)
- Value objects for concepts with no identity (Money, Email, DateRange)
- Organize by bounded context, not by technical layer
- Keep domain logic in entities/services, not in controllers or repositories
Multi-Tenancy
Only when row Tenancy = yes. Without it, do not add tenancy; raise it as a planning question instead.
- ALWAYS filter by the recorded tenant key (e.g.
account_id) at the data-access level - Tenant ID extracted from auth context (JWT/session), NEVER from request body
- Super Admin may access cross-tenant data — explicitly guard this
- NEVER trust client-provided tenant ID
Configuration
- NEVER read the environment directly in services (e.g.
process.env) - ALWAYS use a centralized, typed configuration service/module
Rules:
- Define a configuration interface with typed properties
- Load and validate config at startup
- Inject config service into consumers
- Fail fast on missing required config
KISS and YAGNI
- Don't add abstraction layers you don't need yet
- Don't implement patterns the project doesn't use
- Prefer simple, readable code over clever code
- Add complexity only when requirements demand it
- Follow existing project patterns — consistency over personal preference
Validation Checklist
RESTful Standards
- [ ] URLs use nouns, not verbs (no
/getUsers,/createOrder) - [ ] Correct HTTP methods (GET=read, POST=create, PUT=full update, PATCH=partial, DELETE=remove)
- [ ] Correct status codes (POST→201, DELETE→204, GET/PUT/PATCH→200)
- [ ] URL pattern follows the project's URL/versioning convention
Clean Architecture
- [ ] Layer dependencies respected (the project's layering; the example order if none is recorded)
- [ ] Domain has zero I/O or framework dependencies
- [ ] If the project uses repositories: they return domain entities, not DTOs or raw rows
Dependency Injection
- [ ] If the project uses a DI container: all services/repositories/handlers registered in it
- [ ] Dependencies injected via constructor/parameters, not instantiated directly
- [ ] Services depend on interfaces, not concrete implementations
- [ ] If the project uses a DI container: cross-module dependencies explicitly exported/shared
DTOs
- [ ] Naming follows convention (Create/Update/Patch/Response + EntityDto)
- [ ] Validation rules on all input DTO fields
- [ ] Response DTOs exist for read operations
Error Handling
- [ ] Services throw domain errors, not HTTP exceptions
- [ ] Presentation layer maps domain errors to HTTP responses
- [ ] Domain errors are descriptive and typed
Multi-Tenancy
- [ ] If the project uses tenancy: every query filters by the recorded tenant key
- [ ] If the project uses tenancy: tenant ID extracted from auth context, never from request body
- [ ] If the project uses tenancy: client-provided tenant ID never trusted
Configuration
- [ ] Uses centralized config service, never direct env var access