Skip to content

Vertical Slice Architecture ​

This guide details the architectural philosophy governing the BeechCMS monorepo (apps/api, apps/dashboard, and packages). It provides concrete patterns and invariants for building isolated, maintainable features.


Foundational Principles ​

Traditional layered architectures organize code horizontally by technical tier (controllers, services, repositories). Vertical Slice Architecture (VSA) groups code vertically by business feature:

Layered vs Vertical Slice Architecture Comparison

The Golden Rule: High cohesion inside a feature slice, zero direct coupling between sibling slices.


Anatomy of an API Slice (apps/api/src/features/<slice>/) ​

Each API feature lives in an isolated folder under apps/api/src/features/:

text
apps/api/src/features/content/
├── index.ts              # Feature entry point: mounts scoped Hono sub-app
├── constants.ts          # Feature-scoped strings and error identifiers
└── handlers/             # Thin route handlers
    ├── list.ts
    ├── get.ts
    ├── create.ts
    ├── update.ts
    ├── delete.ts
    ├── helpers.ts        # Shared validation/serialization for this slice
    └── …                 # bulk, facets, kanban-move, view-config

1. The Thin Handler Pattern ​

Route handlers in BeechCMS are strictly thin orchestrators. They:

  • Parse and validate inputs (using Zod or Hono validators).
  • Retrieve injected domain services from the Hono context via c.get(...).
  • Delegate business logic to the service.
  • Return standard JSON responses or RFC 9457 Problem Details for errors.

Rule: Handlers must NEVER contain raw SQL strings or execute direct D1 queries.

typescript
// apps/api/src/features/content/handlers/get.ts
import type { Context } from 'hono'
import type { Env, Variables } from '../../../types'

export async function getHandler(c: Context<{ Bindings: Env; Variables: Variables }>) {
  const seedSlug = c.req.param('slug')
  const entryId = c.req.param('id')

  // Retrieve injected repository service
  const repository = c.get('repository')

  const entry = await repository.getById(seedSlug, entryId)
  if (!entry) {
    return c.json(
      {
        type: 'https://beechcms.dev/errors/not-found',
        title: 'Entry Not Found',
        status: 404,
        detail: `Entry ${entryId} was not found in seed ${seedSlug}`
      },
      404
    )
  }

  return c.json({ data: entry })
}

2. Middleware & Interface Injection ​

To eliminate cross-slice dependencies:

  • Abstract service interfaces (e.g. ContentRepository, ISeedRepository, IBackrefRepository) are defined centrally in @beechcms/core.
  • Concrete database persistence classes live in apps/api/src/shared/db/repositories/ (e.g. D1BackrefRepository implements IBackrefRepository in shared/db/repositories/d1-backref.repository.ts).
  • Repositories are instantiated in global middleware and injected into the Hono context:
typescript
// apps/api/src/middleware/repository.middleware.ts
import { createMiddleware } from 'hono/factory'
import { D1ContentRepository } from '../shared/db/repositories/content.repository.d1'
import { D1BackrefRepository } from '../shared/db/repositories/d1-backref.repository'

export const repositoryMiddleware = (overrides?: RepositoryOverrides) =>
  createMiddleware(async (context, next) => {
    context.set('repository', overrides?.repository ?? new D1ContentRepository(database, overrides?.hooks, privacyService))
    context.set('backrefRepository', overrides?.backrefRepository ?? new D1BackrefRepository(database))
    // …every other repository is injected the same way
    await next()
  })

The injected content repository is read back as context.get('repository') — see the handler example above. The back-reference handler likewise reads c.get('backrefRepository').

Code needed by more than one feature (e.g. CONTENT_ERRORS in shared/content/constants.ts, the OCC helper resolveIfMatch in shared/utils/occ.ts) lives in shared/, so features/draft/ never imports from features/content/.


Anatomy of a Dashboard Slice (apps/dashboard/src/features/<slice>/) ​

The React admin dashboard mirrors the backend feature slicing:

text
apps/dashboard/src/features/seed-builder/
├── index.ts              # Public barrel: explicitly exports allowed components
├── api/                  # Slice HTTP client API calls
│   └── seeds.api.ts
├── components/           # Feature-scoped UI components
│   ├── SeedBuilderPage.tsx
│   ├── SeedDangerZone.tsx
│   └── DeleteSeedDialog.tsx
├── hooks/                # TanStack Query hooks
│   ├── use-seeds.ts
│   └── use-seed-editor-dialog.tsx
└── lib/                  # Slice-local helpers

The Public Barrel Rule ​

A slice's index.ts is its only public contract. External parts of the dashboard may ONLY import what is explicitly exported from the slice barrel:

typescript
// VALID: importing through public barrel
import { SeedBuilderPage, useSeeds } from '@/features/seed-builder'

// INVALID (VETO): deep import into sibling feature slice internals
// (DeleteSeedDialog is deliberately absent from the barrel — it is slice-private)
import { DeleteSeedDialog } from '@/features/seed-builder/components/DeleteSeedDialog'

1. The Thin Page Orchestrator Pattern (apps/dashboard/src/pages/) ​

Mirroring the backend Thin Handler Pattern, route-level pages in apps/dashboard/src/pages/ are strictly composition roots:

  • Extract router parameters and query strings (useParams, useSearchParams).
  • Render the outermost shell layout (AppShell: SidebarProvider, AppSidebar, SidebarInset).
  • Delegate domain logic, UI state, and views to feature-scoped hooks and components.
  • Rule: Page files must remain thin (< 150 lines) and avoid inlining complex filtering algorithms, table computations, or inline dialog trees.

2. Controller Hooks & Headless State Separation ​

To maintain clear separation between business logic and visual presentation:

  • Zero algorithmic logic in JSX: Data normalizations, DSL filtering, conditional formatting calculations, and multi-step mutations belong in dedicated custom hooks (use*) under features/<slice>/hooks/.
  • Target 2–3 focused hooks per complex view:
    1. Query & Filter Hook: handles search, URL synchronization, facet extraction, and TanStack Query fetching.
    2. View/Table Configuration Hook: handles column definitions, density, sorting, grouping, and styling rules.
    3. Action & Modal Hook: handles selections, batch mutations, and open/close state for slice dialogs.
  • Dedicated Sub-components & Modal Orchestrators: Complex view layouts (e.g., Table vs Kanban vs Gallery) and modal suites must be decomposed into dedicated components under features/<slice>/components/.

Dependency Boundaries Matrix ​

Vertical Slice Architecture Dependency Boundaries

FromToAllowed?Rationale
factory.ts (API root)features/<feature>✅ YESComposition root mounts all feature sub-apps.
features/<feature>@beechcms/core✅ YESShared interfaces, Zod schemas, and engine contracts.
features/<feature>shared/ (API)✅ YESShared utilities, auth middleware, and common types.
features/<A>features/<B>❌ NO (VETO)Features must never import sibling feature slices directly.
@beechcms/coreapps/api❌ NO (VETO)Core engine must never depend on application consumers.
handlers/*c.env.DB❌ NO (VETO)Handlers must not execute raw SQL queries on D1 directly.

Anti-Patterns to Avoid ​

  1. Direct SQL / D1 Queries in Handlers: Bypasses Botanical Engine serialization (apiToDb / dbToApi) and breaks column security policies.
  2. Cross-Slice Imports: Feature A (features/content/) must never import from Feature B (features/auth/). Shared contracts belong in @beechcms/core or shared/.
  3. Synchronous Side-Effects: Do not trigger long-running email delivery or remote webhooks synchronously inside request handlers; use c.executionCtx.waitUntil() or queues.
  4. Nested Barrels ("Barrel-inside-Barrel"): Creating chains of pass-through barrels (index.ts in every internal subfolder) obscures source definitions, degrades tree-shaking, and complicates IDE navigation.

Internal Slice Organization: Thematic Clustering vs. Nested Sub-Slices ​

When an architectural slice or core module (such as packages/core/src/engine/ or apps/api/src/public/) contains numerous cohesive files, internal subdirectories are organized by thematic clustering of files (e.g., seeds/, privacy/, ddl/, query/, introspection/, localization/, middleware/, handlers/, relations/, errors/, validation/, utils/) rather than being treated as autonomous nested sub-slices with redundant internal index.ts barrels.

Guidelines for Thematic Clustering: ​

  1. AI & Human Bounded Context: The primary objective is to group related files so that AI assistants and engineers can operate within a tightly focused context window (e.g., viewing only engine/privacy/ when dealing with data classification and encryption, or public/relations/ when resolving nested relation filters, without loading unrelated handlers or DDL).
  2. No Intermediate Barrels: Avoid generating intermediate index.ts barrels inside thematic subfolders. Root modules and barrels export directly from the concrete domain files (e.g., export * from './engine/seeds/define-seed.js' or export { publicRoutes } from './handlers/public-routes.js').
  3. Direct Navigation: TypeScript language servers and IDEs jump directly to the target implementation file rather than through multiple layers of re-export shims.

Ponytail Architectural VETO Checklist ​

Before submitting code, verify compliance against the VETO invariants:

  • [ ] Botanical Dialect: All content reads and mutations pass through @beechcms/core serialization. Zero raw SQLite queries touch content tables directly.
  • [ ] Branch ID Stability: Fields are referenced internally by permanent Branch IDs (br_XX), never hardcoded alias strings.
  • [ ] Slice Isolation: Zero imports between sibling slices under apps/api/src/features/ or apps/dashboard/src/features/.
  • [ ] Thin Handlers: Every API handler delegates database operations to injected repository contracts.
  • [ ] RFC 9457 Errors: All non-2xx responses conform to RFC 9457 Problem Details specifications.