
System Architecture
- 98 installs
- 8 repo stars
- Updated February 6, 2026
- hieutrtr/ai1-skills
System architecture guidance for Python/React projects: component boundaries, service-layer design, data flow, schema planning, and ADRs.
About
Provides design-phase architecture guidance covering FastAPI layer architecture, React component hierarchy, state management, and cross-cutting concerns, producing architecture docs and ADRs. A developer uses it when making system-level architectural decisions.
- FastAPI Routes/Services/Repositories/Models layering
- Produces architecture documents and ADRs
System Architecture by the numbers
- 98 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #2,998 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/hieutrtr/ai1-skills --skill system-architectureAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 98 |
|---|---|
| repo stars | ★ 8 |
| Last updated | February 6, 2026 |
| Repository | hieutrtr/ai1-skills ↗ |
What it does
System architecture guidance for Python/React projects: component boundaries, service-layer design, data flow, schema planning, and ADRs.
Files
System Architecture
When to Use
Activate this skill when:
- Designing a new module, service, or major feature that requires structural decisions
- Choosing between architectural approaches (e.g., where to place logic, how to structure data flow)
- Planning database schema changes or refactoring existing schema
- Making frontend state management decisions (server state vs client state, context vs store)
- Evaluating technology trade-offs for a new capability
- Creating or reviewing Architecture Decision Records (ADRs)
- Setting up a new project or major subsystem from scratch
Input: If plan.md exists (from project-planner), read it for context about the feature scope and affected modules. Otherwise, work from the user's request directly.
Output: Write architecture decisions to architecture.md and create ADRs in docs/adr/ADR-NNN-<title>.md. Tell the user: "Architecture written to architecture.md. Run /api-design-patterns for API contracts or /task-decomposition for implementation tasks."
Do NOT use this skill for:
- Writing implementation code (use
python-backend-expertorreact-frontend-expert) - API contract design or endpoint specifications (use
api-design-patterns) - Testing patterns or strategies (use
pytest-patternsorreact-testing-patterns) - Deployment or infrastructure decisions (use
docker-best-practicesordeployment-pipeline)
Instructions
Project Layer Architecture
The standard Python/React full-stack architecture follows a layered pattern with strict dependency direction.
Backend Layers (FastAPI)
HTTP Request
↓
┌─────────────────────┐
│ Routers (routes/) │ ← HTTP concerns: request parsing, response formatting, status codes
│ │ Uses: Depends() for injection, Pydantic schemas for validation
├─────────────────────┤
│ Services │ ← Business logic: orchestration, validation rules, domain operations
│ (services/) │ No HTTP awareness. Raises domain exceptions, not HTTPException.
├─────────────────────┤
│ Repositories │ ← Data access: queries, CRUD operations, database interactions
│ (repositories/) │ No business logic. Returns model instances or None.
├─────────────────────┤
│ Models (models/) │ ← SQLAlchemy ORM models: table definitions, relationships, indexes
│ Schemas (schemas/) │ ← Pydantic v2 models: request/response contracts, validation
└─────────────────────┘
↓
DatabaseDependency direction rules:
- Routers depend on Services (never on Repositories directly)
- Services depend on Repositories (never on Routers)
- Repositories depend on Models (never on Services)
- Schemas are shared across layers but define no dependencies themselves
- Never skip layers: no direct database access from routes
Dependency injection pattern:
# Router depends on Service via Depends()
@router.post("/users", response_model=UserResponse)
async def create_user(
data: UserCreate,
service: UserService = Depends(get_user_service),
) -> UserResponse:
return await service.create_user(data)
# Service depends on Repository via constructor injection
class UserService:
def __init__(self, repo: UserRepository) -> None:
self.repo = repo
# Repository depends on AsyncSession via Depends()
class UserRepository:
def __init__(self, session: AsyncSession) -> None:
self.session = sessionFrontend Layers (React/TypeScript)
┌─────────────────────┐
│ Pages (pages/) │ ← Route-level components: data fetching, layout composition
├─────────────────────┤
│ Layouts │ ← Page structure: navigation, sidebars, content areas
│ (layouts/) │
├─────────────────────┤
│ Features │ ← Domain-specific: UserProfile, OrderList, ChatPanel
│ (features/) │ Composed from shared components + hooks
├─────────────────────┤
│ Shared Components │ ← Reusable UI: Button, Modal, Table, Form, Input
│ (components/) │ No business logic. Configurable via props.
├─────────────────────┤
│ Hooks (hooks/) │ ← Custom hooks: useAuth, usePagination, useDebounce
│ API (api/) │ ← API client functions, TanStack Query configurations
├─────────────────────┤
│ Types (types/) │ ← Shared TypeScript interfaces and type definitions
└─────────────────────┘Component dependency direction:
- Pages import Features and Layouts
- Features import Shared Components and Hooks
- Shared Components import only other Shared Components and Types
- Hooks import API functions and Types
- API functions import Types only
Decision Framework
When facing architectural decisions, follow this structured process:
Step 1: Define the Problem
- What capability is needed?
- What are the non-functional requirements? (performance, scalability, maintainability)
- What constraints exist? (team size, timeline, existing infrastructure)
Step 2: Identify Options
- List 2-3 viable architectural approaches
- For each option, document:
- How it works (brief technical description)
- Advantages
- Disadvantages
- Risks
Step 3: Evaluate Against Criteria
| Criterion | Weight | Description |
|---|---|---|
| Maintainability | High | Can the team understand, modify, and debug this easily? |
| Testability | High | Can each component be tested in isolation? |
| Performance | Medium | Does it meet latency and throughput requirements? |
| Team familiarity | Medium | Does the team have experience with this approach? |
| Operational cost | Low | What are the infrastructure and maintenance costs? |
| Future flexibility | Low | How easily can this evolve as requirements change? |
Step 4: Decide and Document
- Choose the option that best satisfies the weighted criteria
- Document the decision in an ADR (see
references/architecture-decision-record-template.md) - Record what was NOT chosen and why — this context is valuable for future decisions
Step 5: Communicate
- Share the ADR with the team
- Identify any migration or rollout steps needed
- Flag reversibility: is this a one-way door or a two-way door?
Database Schema Design
Design Principles
1. Start normalized (3NF) — Denormalize only for proven performance bottlenecks, not speculation 2. One migration per logical change — Each Alembic migration should represent a single, coherent schema modification 3. Always include downgrade — Every migration must have a working downgrade() function 4. Index strategically:
- Primary keys (automatic)
- Foreign keys (always)
- Columns in WHERE clauses of frequent queries
- Composite indexes for multi-column lookups
- Partial indexes for filtered queries (e.g.,
WHERE is_active = true)
SQLAlchemy 2.0 Async Patterns
# Model definition with Mapped types (SQLAlchemy 2.0 style)
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
is_active: Mapped[bool] = mapped_column(default=True)
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
# Relationships: ALWAYS use eager loading with async
posts: Mapped[list["Post"]] = relationship(
back_populates="author",
lazy="selectin", # or "joined" — NEVER "lazy" with async
)Async session rules:
- One
AsyncSessionper request — never share across concurrent tasks - Use
async withcontext manager for automatic cleanup - Map session boundaries to transaction boundaries
- Use
selectinorjoinedloading — lazy loading is incompatible with asyncio - Use
run_sync()only as a last resort for legacy code
Migration Planning
1. Schema change → Generate migration: alembic revision --autogenerate -m "description" 2. Review generated migration — verify column types, indexes, constraints 3. Test upgrade: alembic upgrade head 4. Test downgrade: alembic downgrade -1 5. Test data preservation: ensure existing data survives the round-trip
Frontend Architecture
State Management Decision Tree
Is the data from the server?
├── YES → Use TanStack Query (useQuery, useMutation)
│ Configure staleTime, gcTime, query keys
│
└── NO → Is it needed across multiple components?
├── YES → Is it complex with actions/reducers?
│ ├── YES → Use Zustand store
│ └── NO → Use React Context
│
└── NO → Use useState / useReducer locallyTanStack Query conventions:
- Query keys:
[resource, ...identifiers](e.g.,["users", userId],["posts", { page, limit }]) - Use
queryOptions()factory to centralize key + fn definitions — prevents copy-paste key errors - Set
staleTimebased on data freshness needs (default 0 is too aggressive for most cases) - Invalidate with
invalidateQueries()after mutations — never manualrefetch() - Handle all states:
isPending,isError,data
Component design rules:
- Props for configuration, hooks for data
- Lift state only as high as needed — no premature context creation
- Keep components under 200 lines — extract sub-components or custom hooks when larger
- Use
childrenand composition over deep prop drilling
Routing Structure
Organize routes to mirror the URL structure:
src/
├── pages/
│ ├── HomePage.tsx → /
│ ├── LoginPage.tsx → /login
│ ├── users/
│ │ ├── UserListPage.tsx → /users
│ │ └── UserDetailPage.tsx → /users/:id
│ └── settings/
│ └── SettingsPage.tsx → /settingsCross-Cutting Concerns
Authentication Flow
Login Request
↓
Backend: Validate credentials → Generate JWT (access + refresh tokens)
↓
Frontend: Store access token in memory, refresh token in httpOnly cookie
↓
API Calls: Attach access token via Authorization header
↓
Token Expired: Use refresh token to obtain new access token
↓
Refresh Failed: Redirect to loginArchitecture decisions for auth:
- Access tokens: short-lived (15-30 min), stored in memory (not localStorage)
- Refresh tokens: longer-lived (7-30 days), stored in httpOnly cookie
- Backend: FastAPI
Depends()chain for token validation → user extraction → permission check - Frontend: Auth context providing
user,login(),logout(),isAuthenticated
Error Handling Strategy
Errors should be handled at the appropriate layer:
| Layer | Error Type | Action |
|---|---|---|
| Router | HTTPException | Return HTTP error response with status code |
| Service | Domain exceptions | Raise custom exceptions (e.g., UserNotFoundError) |
| Repository | Database exceptions | Catch and re-raise as domain exceptions or let propagate |
| Frontend | API errors | Display user-friendly messages, retry where appropriate |
Backend exception hierarchy:
class AppError(Exception):
"""Base application error."""
class NotFoundError(AppError):
"""Resource not found."""
class ConflictError(AppError):
"""Resource conflict (duplicate, version mismatch)."""
class ValidationError(AppError):
"""Business rule violation."""Router-level exception handler maps domain exceptions to HTTP responses:
@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError):
return JSONResponse(status_code=404, content={"detail": str(exc)})Logging Architecture
Backend (structlog):
- Structured JSON logs in production
- Human-readable console in development
- Bind request context (request_id, user_id) at middleware level
- Log at service layer (business events), not repository layer (too noisy)
- Use log levels: DEBUG (development only), INFO (business events), WARNING (recoverable issues), ERROR (failures requiring attention)
Frontend:
console.*in development- Structured error reporting to backend or Sentry in production
- Log user actions for debugging, not for analytics
Configuration Management
Backend (pydantic-settings):
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
database_url: str
redis_url: str = "redis://localhost:6379"
jwt_secret: str
debug: bool = FalseFrontend (environment variables):
VITE_API_URLfor API base URL- Build-time injection via Vite's
import.meta.env - No secrets in frontend environment variables
Output Files
architecture.md
Write the architecture document to architecture.md at the project root:
# Architecture: [Feature/System Name]
## Overview
[1-2 sentence summary of the architectural approach]
## Layer Structure
[Backend and frontend layer descriptions from this skill's patterns]
## Key Decisions
[Summary of decisions made, with links to ADRs]
## Database Schema
[Entity descriptions, relationships, key indexes]
## Cross-Cutting Concerns
[Auth, error handling, logging approach]
## Next Steps
- Run `/api-design-patterns` to define API contracts
- Run `/task-decomposition` to create implementation tasksADRs
For each significant decision, create an ADR in docs/adr/:
# ADR-NNN: [Decision Title]
## Status
Accepted | Proposed | Superseded
## Context
[Why this decision is needed]
## Decision
[What we decided]
## Consequences
[Positive and negative outcomes]Number ADRs sequentially (ADR-001, ADR-002, etc.).
Examples
Architecture Decision: Real-Time Notifications
Problem: The application needs real-time notifications for users (new messages, status updates).
Options evaluated:
| Option | Pros | Cons |
|---|---|---|
| WebSocket | True bidirectional, low latency | Complex connection management, harder to scale |
| Server-Sent Events (SSE) | Simple, HTTP-based, auto-reconnect | Unidirectional (server→client only), limited browser connections |
| Polling | Simplest implementation, works everywhere | Higher latency, unnecessary server load |
Decision: WebSocket for this use case.
Rationale: Notifications require low latency and the system will eventually need bidirectional communication (typing indicators, presence). SSE would work for notifications alone but would require a separate solution for future bidirectional needs. Polling introduces unacceptable latency for real-time UX.
Architecture:
- Backend: FastAPI WebSocket endpoint with
ConnectionManagerclass - Frontend: Custom
useWebSockethook with automatic reconnection - Scaling: Redis pub/sub for multi-instance message distribution
- Persistence: Store notifications in database for offline users
- Fallback: REST endpoint for notification history and initial load
See references/architecture-decision-record-template.md for the full ADR format.
Edge Cases
Monolith vs Microservices
Default to modular monolith for teams smaller than 10 developers. A modular monolith provides:
- Clear module boundaries without network overhead
- Shared database with module-specific schemas
- Easy refactoring and code navigation
- Simple deployment and debugging
Consider microservices only when:
- Independent scaling is required for specific components
- Different modules need different technology stacks
- Team size exceeds 10 and ownership boundaries are clear
- Deployment independence is a business requirement
Migration path: Design module boundaries in the monolith as if they were services (no direct cross-module database access, communicate via service interfaces). This makes extraction to microservices straightforward when needed.
When to Break the Layer Pattern
The strict Router → Service → Repository pattern should be followed for standard CRUD operations. Acceptable exceptions:
- Background tasks: May call services directly without going through a router
- Event handlers: Domain event listeners may call services from any context
- CLI commands: Management scripts may access services or repositories directly
- Migrations: Data migrations may access models directly (no service/repo layer needed)
- Health checks: May access the database directly for simple connectivity verification
In all cases, business logic should still live in the service layer — these exceptions are about the entry point, not about bypassing business rules.
Evolving Architecture
When the architecture needs to change: 1. Write an ADR documenting the motivation and the proposed change 2. Identify all affected modules and their dependencies 3. Plan an incremental migration — never big-bang rewrites 4. Maintain backward compatibility during transition (strangler fig pattern) 5. Set a deadline for completing the migration and removing legacy code
Architecture Decision Record Template
Use this template to document architectural decisions. Store ADRs in a docs/adr/ directory in the project root, numbered sequentially (e.g., 001-use-postgresql.md).
---
ADR-NNN: [Short Title]
Status: [Proposed | Accepted | Deprecated | Superseded by ADR-NNN]
Date: YYYY-MM-DD
Deciders: [List of people involved in the decision]
---
Context
Describe the situation that requires a decision. Include:
- What is the problem or opportunity?
- What are the constraints (technical, business, timeline)?
- What forces are at play (team skills, existing infrastructure, dependencies)?
Example:
The application needs to store user-uploaded files. Currently files are stored on the local filesystem, which does not scale across multiple application instances. We need a shared storage solution that supports the expected growth from 1,000 to 100,000 users within the next year.
---
Decision
State the decision clearly in one sentence, then elaborate on the details.
Example:
We will use Amazon S3 for file storage, accessed via the aioboto3 library for async operations.Details:
- Files will be organized by
user_id/year/month/filename - Access will be via presigned URLs with 1-hour expiration
- Maximum file size: 50MB (enforced at upload)
- Allowed MIME types: images (JPEG, PNG, WebP), documents (PDF)
---
Options Considered
Option 1: [Name]
- Description: Brief technical description
- Pros: List advantages
- Cons: List disadvantages
- Estimated effort: [trivial / small / medium / large]
Option 2: [Name]
- Description: Brief technical description
- Pros: List advantages
- Cons: List disadvantages
- Estimated effort: [trivial / small / medium / large]
Option 3: [Name] (if applicable)
- Description: Brief technical description
- Pros: List advantages
- Cons: List disadvantages
- Estimated effort: [trivial / small / medium / large]
---
Evaluation Criteria
| Criterion | Weight | Option 1 | Option 2 | Option 3 |
|---|---|---|---|---|
| Maintainability | High | |||
| Testability | High | |||
| Performance | Medium | |||
| Team familiarity | Medium | |||
| Operational cost | Low |
---
Consequences
Positive
- List expected benefits of this decision
Negative
- List expected drawbacks or trade-offs
Risks
- List risks and their mitigations
---
Reversibility
Is this a one-way or two-way door?
- One-way door: Difficult or expensive to reverse (e.g., database engine change, programming language switch). Requires careful consideration.
- Two-way door: Easy to reverse if it doesn't work out (e.g., library choice, caching strategy). Prefer fast execution over extensive analysis.
---
Follow-Up Actions
- [ ] Action 1: [Description] — Owner: [Name] — Due: [Date]
- [ ] Action 2: [Description] — Owner: [Name] — Due: [Date]
---
References
- [Link to relevant documentation]
- [Link to related ADRs]
- [Link to technical research or benchmarks]
---
ADR Lifecycle
1. Proposed — Draft written, under discussion 2. Accepted — Team agrees, ready for implementation 3. Deprecated — No longer relevant (explain why in the document) 4. Superseded — Replaced by a newer ADR (link to the replacement)
Keep all ADRs in the repository, even deprecated ones. They provide valuable historical context for future decisions.
Layer Responsibilities Guide
Detailed guide on what belongs in each layer of the FastAPI + React/TypeScript architecture. Use this reference when deciding where to place new code.
---
Backend Layers
Routes (Routers)
Location: app/routes/ or app/api/
Responsibility: HTTP interface — translate between HTTP and the application domain.
DOES:
- Parse and validate request data using Pydantic schemas
- Call service methods with validated data
- Return HTTP responses with appropriate status codes
- Handle HTTP-specific concerns (headers, cookies, content negotiation)
- Define FastAPI route decorators (
@router.get,@router.post, etc.) - Use
Depends()for dependency injection (auth, services, pagination) - Map domain exceptions to HTTP status codes via exception handlers
DOES NOT:
- Contain business logic or domain rules
- Access the database directly
- Import repository classes
- Transform data beyond HTTP serialization
- Make decisions about application behavior
Example:
@router.post("/users", status_code=201, response_model=UserResponse)
async def create_user(
data: UserCreate,
service: UserService = Depends(get_user_service),
) -> UserResponse:
# Route only delegates to service — no logic here
user = await service.create_user(data)
return UserResponse.model_validate(user)---
Services
Location: app/services/
Responsibility: Business logic — the core of the application.
DOES:
- Implement business rules and domain logic
- Orchestrate operations across multiple repositories
- Validate business constraints (e.g., "user must have verified email to post")
- Raise domain-specific exceptions (
NotFoundError,ConflictError) - Coordinate transactions when multiple writes are needed
- Emit domain events (if using event-driven patterns)
- Apply authorization rules ("can this user perform this action?")
DOES NOT:
- Know about HTTP (no
Request,Response,HTTPException, status codes) - Execute raw SQL queries
- Import route modules
- Handle serialization to/from JSON
- Manage database sessions directly (receive via injection)
Example:
class UserService:
def __init__(self, repo: UserRepository, email_service: EmailService) -> None:
self.repo = repo
self.email_service = email_service
async def create_user(self, data: UserCreate) -> User:
# Business rule: check for duplicate email
existing = await self.repo.get_by_email(data.email)
if existing:
raise ConflictError(f"Email {data.email} already registered")
# Business logic: hash password, create user
hashed = hash_password(data.password)
user = await self.repo.create(email=data.email, hashed_password=hashed)
# Side effect: send welcome email
await self.email_service.send_welcome(user.email)
return user---
Repositories
Location: app/repositories/
Responsibility: Data access — encapsulate all database interactions.
DOES:
- Execute database queries (SELECT, INSERT, UPDATE, DELETE)
- Use SQLAlchemy ORM or Core for query construction
- Handle query optimization (eager loading, pagination, filtering)
- Return model instances, lists, or None
- Apply database-level constraints (unique checks via queries)
- Manage query-level concerns (ordering, limiting, offsetting)
DOES NOT:
- Contain business logic or validation rules
- Raise domain exceptions (raise data-layer exceptions or return None)
- Know about HTTP or API contracts
- Import service classes
- Handle transactions (the service or middleware manages transaction scope)
- Transform data into response formats
Example:
class UserRepository:
def __init__(self, session: AsyncSession) -> None:
self.session = session
async def get_by_id(self, user_id: int) -> User | None:
result = await self.session.execute(
select(User).where(User.id == user_id)
)
return result.scalar_one_or_none()
async def get_by_email(self, email: str) -> User | None:
result = await self.session.execute(
select(User).where(User.email == email)
)
return result.scalar_one_or_none()
async def create(self, **kwargs) -> User:
user = User(**kwargs)
self.session.add(user)
await self.session.flush() # Get the ID without committing
return user---
Models
Location: app/models/
Responsibility: Database schema definition — map Python classes to database tables.
DOES:
- Define table columns with types, constraints, and defaults
- Define relationships between tables (foreign keys, back_populates)
- Define indexes (single-column, composite, partial)
- Use SQLAlchemy 2.0
Mappedtype annotations - Specify eager loading strategy on relationships (
lazy="selectin"for async)
DOES NOT:
- Contain business logic or methods
- Import services or repositories
- Define API-facing schemas (that's Pydantic's job)
- Manage sessions or transactions
Conventions:
- Table names: plural snake_case (
users,blog_posts) - Column names: snake_case (
created_at,is_active) - Always set
lazy="selectin"orlazy="joined"for async compatibility - Use
server_defaultfor database-level defaults (e.g.,func.now()) - Define
__repr__for debugging convenience
---
Schemas (Pydantic v2)
Location: app/schemas/
Responsibility: Data validation and serialization — define the shape of data at API boundaries.
DOES:
- Validate request data (types, constraints, formats)
- Define response shapes (what fields are exposed to the client)
- Apply field-level validation (min/max length, regex, email format)
- Apply model-level validation (cross-field constraints)
- Provide serialization/deserialization between JSON and Python objects
DOES NOT:
- Contain business logic
- Access the database
- Import models directly (use
model_validate()for ORM → schema conversion)
Naming conventions:
{Resource}Create— POST request body (e.g.,UserCreate){Resource}Update— PUT/PATCH request body (e.g.,UserUpdate){Resource}Response— Response body (e.g.,UserResponse){Resource}Filter— Query parameters for filtering (e.g.,UserFilter){Resource}ListResponse— Paginated list response (e.g.,UserListResponse)
---
Frontend Layers
Pages
Location: src/pages/
Responsibility: Route-level components — compose features and layouts for a URL.
DOES:
- Fetch data needed for the page (via TanStack Query hooks)
- Compose layout and feature components
- Handle page-level loading and error states
- Define page metadata (title, description)
DOES NOT:
- Contain reusable UI components
- Define data fetching logic (that lives in hooks)
- Implement complex business logic
---
Features
Location: src/features/
Responsibility: Domain-specific UI — composed from shared components and hooks.
DOES:
- Implement domain-specific UI (UserProfile, OrderList, ChatPanel)
- Use custom hooks for data and state management
- Compose shared components with domain-specific props
- Handle feature-specific interactions and state
DOES NOT:
- Make direct API calls (use hooks)
- Define reusable generic components (those go in
components/)
---
Shared Components
Location: src/components/
Responsibility: Reusable UI primitives — generic, configurable via props.
DOES:
- Render UI elements (Button, Modal, Table, Form, Input, Card)
- Accept configuration via props (variant, size, disabled, onClick)
- Handle visual states (hover, focus, loading, disabled)
- Implement accessibility (ARIA attributes, keyboard navigation)
DOES NOT:
- Fetch data or manage server state
- Contain business logic
- Import feature-level components
---
Hooks
Location: src/hooks/
Responsibility: Reusable stateful logic — abstract away complexity from components.
DOES:
- Wrap TanStack Query calls (useQuery, useMutation)
- Manage complex local state (useReducer patterns)
- Encapsulate browser API interactions (useMediaQuery, useLocalStorage)
- Provide domain-specific logic (useAuth, usePagination, useDebounce)
Naming: Always prefix with use (e.g., useAuth, useUsers, useDebounce)
---
API Layer
Location: src/api/
Responsibility: API client — define how to communicate with the backend.
DOES:
- Define API endpoint functions (e.g.,
fetchUsers,createUser) - Configure HTTP client (axios/fetch with base URL, interceptors)
- Define TanStack Query options using
queryOptions()factory - Handle token injection and refresh
DOES NOT:
- Manage UI state
- Handle errors (let TanStack Query and components handle display)
---
Decision Guide: Where Does This Code Go?
| If the code... | Put it in... |
|---|---|
| Parses HTTP request or formats HTTP response | Routes |
| Enforces a business rule | Services |
| Queries or writes to the database | Repositories |
| Defines a table schema | Models |
| Validates input or shapes output | Schemas |
| Composes UI for a URL | Pages |
| Implements domain-specific UI | Features |
| Is a reusable UI element | Shared Components |
| Manages stateful logic for components | Hooks |
| Calls the backend API | API Layer |