---
name: ecc-backend-patterns
description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.
---

# Backend Patterns

Backend architecture patterns for Node.js and modern frameworks.

## When to Activate
- Designing backend architecture
- Setting up API routes and middleware
- Optimizing database queries
- Reviewing backend code

## Architecture Layers
```
Routes (thin) → Controllers → Services → Repositories → Database
```

### Route Layer
- Parse & validate request
- Call controller
- Format response

### Service Layer
- Business logic
- Orchestration of multiple operations
- No direct DB access

### Repository Layer
- Database queries only
- No business logic

## API Route Structure
```typescript
// routes/users.ts
import { Router } from 'express';
const router = Router();

router.get('/', async (req, res) => {
  const users = await userService.list(req.query);
  res.json({ data: users });
});

router.post('/', validate(createUserSchema), async (req, res) => {
  const user = await userService.create(req.body);
  res.status(201).json({ data: user });
});
```

## Middleware Order
1. Security (helmet, cors)
2. Parsing (json, urlencoded)
3. Logging (request logger)
4. Auth (session, JWT)
5. Rate limiting
6. Routes
7. Error handler (last!)

## Best Practices
- All I/O is async
- Controllers never access req/res directly
- Services return typed results
- All errors go through centralized error handler
- Environment-based config (not hardcoded values)
