Full-Stack Development Practices
MANDATORY WORKFLOW — Follow These Steps In Order
When this skill is triggered, you MUST follow this workflow before writing any code.
Step 0: Gather Requirements
Before scaffolding anything, ask the user to clarify (or infer from context):
- 1. Stack: Language/framework for backend and frontend (e.g., Express + React, Django + Vue, Go + HTMX)
- Service type: API-only, full-stack monolith, or microservice?
- Database: SQL (PostgreSQL, SQLite, MySQL) or NoSQL (MongoDB, Redis)?
- Integration: REST, GraphQL, tRPC, or gRPC?
- Real-time: Needed? If yes — SSE, WebSocket, or polling?
- Auth: Needed? If yes — JWT, session, OAuth, or third-party (Clerk, Auth.js)?
If the user has already specified these in their request, skip asking and proceed.
Step 1: Architectural Decisions
Based on requirements, make and state these decisions before coding:
| Decision | Options | Reference |
|---|
| Project structure | Feature-first (recommended) vs layer-first | Section 1 |
| API client approach |
Typed fetch / React Query / tRPC / OpenAPI codegen |
Section 5 |
| Auth strategy | JWT + refresh / session / third-party |
Section 6 |
| Real-time method | Polling / SSE / WebSocket |
Section 11 |
| Error handling | Typed error hierarchy + global handler |
Section 3 |
Briefly explain each choice (1 sentence per decision).
Step 2: Scaffold with Checklist
Use the appropriate checklist below. Ensure ALL checked items are implemented — do not skip any.
Step 3: Implement Following Patterns
Write code following the patterns in this document. Reference specific sections as you implement each part.
Step 4: Test & Verify
After implementation, run these checks before claiming completion:
- 1. Build check: Ensure both backend and frontend compile without errors
# Backend
cd server && npm run build
# Frontend
cd client && npm run build
- 2. Start & smoke test: Start the server, verify key endpoints return expected responses
# Start server, then test
curl http://localhost:3000/health
curl http://localhost:3000/api/<resource>
- 3. Integration check: Verify frontend can connect to backend (CORS, API base URL, auth flow)
- Real-time check (if applicable): Open two browser tabs, verify changes sync
If any check fails, fix the issue before proceeding.
Step 5: Handoff Summary
Provide a brief summary to the user:
- - What was built: List of implemented features and endpoints
- How to run: Exact commands to start backend and frontend
- What's missing / next steps: Any deferred items, known limitations, or recommended improvements
- Key files: List the most important files the user should know about
Scope
USE this skill when:
- - Building a full-stack application (backend + frontend)
- Scaffolding a new backend service or API
- Designing service layers and module boundaries
- Implementing database access, caching, or background jobs
- Writing error handling, logging, or configuration management
- Reviewing backend code for architectural issues
- Hardening for production
- Setting up API clients, auth flows, file uploads, or real-time features
NOT for:
- - Pure frontend/UI concerns (use your frontend framework's docs)
- Pure database schema design without backend context
Quick Start — New Backend Service Checklist
- - [ ] Project scaffolded with feature-first structure
- [ ] Configuration centralized, env vars validated at startup (fail fast)
- [ ] Typed error hierarchy defined (not generic
Error) - [ ] Global error handler middleware
- [ ] Structured JSON logging with request ID propagation
- [ ] Database: migrations set up, connection pooling configured
- [ ] Input validation on all endpoints (Zod / Pydantic / Go validator)
- [ ] Authentication middleware in place
- [ ] Health check endpoints (
/health, /ready) - [ ] Graceful shutdown handling (SIGTERM)
- [ ] CORS configured (explicit origins, not
*) - [ ] Security headers (helmet or equivalent)
- [ ]
.env.example committed (no real secrets)
Quick Start — Frontend-Backend Integration Checklist
- - [ ] API client configured (typed fetch wrapper, React Query, tRPC, or OpenAPI generated)
- [ ] Base URL from environment variable (not hardcoded)
- [ ] Auth token attached to requests automatically (interceptor / middleware)
- [ ] Error handling — API errors mapped to user-facing messages
- [ ] Loading states handled (skeleton/spinner, not blank screen)
- [ ] Type safety across the boundary (shared types, OpenAPI, or tRPC)
- [ ] CORS configured with explicit origins (not
* in production) - [ ] Refresh token flow implemented (httpOnly cookie + transparent retry on 401)
Quick Navigation
2. Configuration |
| Handle errors properly |
3. Error Handling |
| Write database code |
4. Database Access Patterns |
| Set up API client from frontend |
5. API Client Patterns |
| Add auth middleware |
6. Auth & Middleware |
| Set up logging |
7. Logging & Observability |
| Add background jobs |
8. Background Jobs |
| Implement caching |
9. Caching |
| Upload files (presigned URL, multipart) |
10. File Upload Patterns |
| Add real-time features (SSE, WebSocket) |
11. Real-Time Patterns |
| Handle API errors in frontend UI |
12. Cross-Boundary Error Handling |
| Harden for production |
13. Production Hardening |
| Design API endpoints |
API Design |
| Design database schema |
Database Schema |
| Auth flow (JWT, refresh, Next.js SSR, RBAC) |
references/auth-flow.md |
| CORS, env vars, environment management |
references/environment-management.md |
Core Principles (7 Iron Rules)
CODEBLOCK2
1. Project Structure & Layering (CRITICAL)
Feature-First Organization
CODEBLOCK3
Three-Layer Architecture
CODEBLOCK4
| Layer | Responsibility | ❌ Never |
|---|
| Controller | Parse request, validate, call service, format response | Business logic, DB queries |
| Service |
Business rules, orchestration, transaction mgmt | HTTP types (req/res), direct DB |
| Repository | Database queries, external API calls | Business logic, HTTP types |
Dependency Injection (All Languages)
TypeScript:
CODEBLOCK5
Python:
CODEBLOCK6
Go:
type OrderService struct {
orderRepo OrderRepository // ✅ interface
emailService EmailService
}
func NewOrderService(repo OrderRepository, email EmailService) *OrderService {
return &OrderService{orderRepo: repo, emailService: email}
}
2. Configuration & Environment (CRITICAL)
Centralized, Typed, Fail-Fast
TypeScript:
CODEBLOCK8
Python:
CODEBLOCK9
Rules
CODEBLOCK10
3. Error Handling & Resilience (HIGH)
Typed Error Hierarchy
CODEBLOCK11
CODEBLOCK12
Global Error Handler
CODEBLOCK13
Rules
CODEBLOCK14
4. Database Access Patterns (HIGH)
Migrations Always
CODEBLOCK15
CODEBLOCK16
N+1 Prevention
CODEBLOCK17
Transactions for Multi-Step Writes
CODEBLOCK18
Connection Pooling
Pool size = (CPU cores × 2) + spindle_count (start with 10-20). Always set connection timeout. Use PgBouncer for serverless.
5. API Client Patterns (MEDIUM)
The "glue layer" between frontend and backend. Choose the approach that fits your team and stack.
Option A: Typed Fetch Wrapper (Simple, No Dependencies)
CODEBLOCK19
Option B: React Query + Typed Client (Recommended for React)
CODEBLOCK20
Option C: tRPC (Same Team Owns Both Sides)
CODEBLOCK21
Option D: OpenAPI Generated Client (Public / Multi-Consumer APIs)
CODEBLOCK22
Decision: Which API Client?
| Approach | When | Type Safety | Effort |
|---|
| Typed fetch wrapper | Simple apps, small teams | Manual types | Low |
| React Query + fetch |
React apps, server state | Manual types | Medium |
| tRPC | Same team, TypeScript both sides | Automatic | Low |
| OpenAPI generated | Public API, multi-consumer | Automatic | Medium |
| GraphQL codegen | GraphQL APIs | Automatic | Medium |
6. Authentication & Middleware (HIGH)
Full reference: references/auth-flow.md — JWT bearer flow, automatic token refresh, Next.js server-side auth, RBAC pattern, backend middleware order.
Standard Middleware Order
CODEBLOCK23
JWT Rules
CODEBLOCK24
RBAC Pattern
CODEBLOCK25
Auth Token Automatic Refresh
CODEBLOCK26
7. Logging & Observability (MEDIUM-HIGH)
Structured JSON Logging
CODEBLOCK27
Log Levels
| Level | When | Production? |
|---|
| error | Requires immediate attention | ✅ Always |
| warn |
Unexpected but handled | ✅ Always |
| info | Normal operations, audit trail | ✅ Always |
| debug | Dev troubleshooting | ❌ Dev only |
Rules
CODEBLOCK28
8. Background Jobs & Async (MEDIUM)
Rules
CODEBLOCK29
Idempotent Job Pattern
CODEBLOCK30
9. Caching Patterns (MEDIUM)
Cache-Aside (Lazy Loading)
CODEBLOCK31
Rules
CODEBLOCK32
| Data Type | Suggested TTL |
|---|
| User profile | 5-15 min |
| Product catalog |
1-5 min |
| Config / feature flags | 30-60 sec |
| Session | Match session duration |
10. File Upload Patterns (MEDIUM)
Option A: Presigned URL (Recommended for Large Files)
CODEBLOCK33
Backend:
CODEBLOCK34
Frontend:
CODEBLOCK35
Option B: Multipart (Small Files < 10MB)
CODEBLOCK36
Decision
| Method | File Size | Server Load | Complexity |
|---|
| Presigned URL | Any (recommended > 5MB) | None (direct to storage) | Medium |
| Multipart |
< 10MB | High (streams through server) | Low |
| Chunked / Resumable | > 100MB | Medium | High |
11. Real-Time Patterns (MEDIUM)
Option A: Server-Sent Events (SSE) — One-Way Server → Client
Best for: notifications, live feeds, streaming AI responses.
Backend (Express):
CODEBLOCK37
Frontend:
CODEBLOCK38
Option B: WebSocket — Bidirectional
Best for: chat, collaborative editing, gaming.
Backend (ws library):
CODEBLOCK39
Frontend:
CODEBLOCK40
Option C: Polling (Simplest, No Infrastructure)
CODEBLOCK41
Decision
| Method | Direction | Complexity | When |
|---|
| Polling | Client → Server | Low | Simple status checks, < 10 clients |
| SSE |
Server → Client | Medium | Notifications, feeds, AI streaming |
| WebSocket | Bidirectional | High | Chat, collaboration, gaming |
12. Cross-Boundary Error Handling (MEDIUM)
API Error → User-Facing Message
CODEBLOCK42
React Query Global Error Handler
CODEBLOCK43
Rules
CODEBLOCK44
Integration Decision Tree
CODEBLOCK45
13. Production Hardening (MEDIUM)
Health Checks
CODEBLOCK46
Graceful Shutdown
CODEBLOCK47
Security Checklist
CODEBLOCK48
Anti-Patterns
| # | ❌ Don't | ✅ Do Instead |
|---|
| 1 | Business logic in routes/controllers | Move to service layer |
| 2 |
process.env scattered everywhere | Centralized typed config |
| 3 |
console.log for logging | Structured JSON logger |
| 4 | Generic
Error('oops') | Typed error hierarchy |
| 5 | Direct DB calls in controllers | Repository pattern |
| 6 | No input validation | Validate at boundary (Zod/Pydantic) |
| 7 | Catching errors silently | Log + rethrow or return error |
| 8 | No health check endpoints |
/health +
/ready |
| 9 | Hardcoded config/secrets | Environment variables |
| 10 | No graceful shutdown | Handle SIGTERM properly |
| 11 | Hardcode API URL in frontend | Environment variable (
NEXT_PUBLIC_API_URL) |
| 12 | Store JWT in localStorage | Memory + httpOnly refresh cookie |
| 13 | Show raw API errors to users | Map to human-readable messages |
| 14 | Retry 4xx errors | Only retry 5xx (server failures) |
| 15 | Skip loading states | Skeleton/spinner while fetching |
| 16 | Upload large files through API server | Presigned URL → direct to S3 |
| 17 | Poll for real-time data | SSE or WebSocket |
| 18 | Duplicate types frontend + backend | Shared types, tRPC, or OpenAPI codegen |
Common Issues
Issue 1: "Where does this business rule go?"
Rule: If it involves HTTP (request parsing, status codes, headers) → controller. If it involves business decisions (pricing, permissions, rules) → service. If it touches the database → repository.
Issue 2: "Service is getting too big"
Symptom: One service file > 500 lines with 20+ methods.
Fix: Split by sub-domain. OrderService → OrderCreationService + OrderFulfillmentService + OrderQueryService. Each focused on one workflow.
Issue 3: "Tests are slow because they hit the database"
Fix: Unit tests mock the repository layer (fast). Integration tests use test containers or transaction rollback (real DB, still fast). Never mock the service layer in integration tests.
Reference Documents
This skill includes deep-dive references for specialized topics. Read the relevant reference when you need detailed guidance.
| Need to… | Reference |
|---|
| Write backend tests (unit, integration, e2e, contract, performance) | references/testing-strategy.md |
| Validate a release before deployment (6-gate checklist) |
references/release-checklist.md |
| Choose a tech stack (language, framework, database, infra) |
references/technology-selection.md |
| Build with Django / DRF (models, views, serializers, admin) |
references/django-best-practices.md |
| Design REST/GraphQL/gRPC endpoints (URLs, status codes, pagination) |
references/api-design.md |
| Design database schema, indexes, migrations, multi-tenancy |
references/db-schema.md |
| Auth flow (JWT bearer, token refresh, Next.js SSR, RBAC, middleware order) |
references/auth-flow.md |
| CORS config, env vars per environment, common CORS issues |
references/environment-management.md |