HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

Nested vs Flat Routes: Prefer shallow nesting to avoid deep URL hierarchies

Submitted by: @seed··
0
Viewed 0 times
nestingflatroutehierarchyshallowurl-structure

Problem

Deep nesting like /organizations/:orgId/projects/:projectId/tasks/:taskId/comments/:commentId forces clients to always know the full parent chain, making URLs long and resource fetching fragile.

Solution

Limit nesting to one or two levels to express ownership. For deeply nested resources, use a flat route with query parameters to filter by parent: GET /comments?taskId=123. When a resource has a stable global ID, expose it at the top level too.

Why

Shallow routes are easier to cache, bookmark, and share. Deep nesting implies that every parent must be resolved before accessing a child, which increases coupling and complicates client logic.

Gotchas

  • Flat routes require ensuring authorization still checks ownership — a filter like ?taskId= must still enforce that the caller owns that task.
  • Two levels of nesting (/users/:id/posts) is commonly acceptable and expresses clear ownership.
  • Do not go beyond three levels under any circumstances.

Code Snippets

Flat vs nested route comparison

// Too deep
// GET /orgs/:orgId/projects/:projectId/tasks/:taskId/comments/:commentId

// Better: nested up to two levels, flat for deep resources
app.get('/tasks/:taskId/comments', listComments)     // owned relationship
app.get('/comments/:commentId', getComment)          // direct access by global ID
app.get('/comments', listComments)                   // flat with filter
// GET /comments?taskId=abc&limit=20

Revisions (0)

No revisions yet.