deckhearth/.cursor/skills/add-api-route/SKILL.md
Randall Stillwell bb05ca731b bootstrap: agent pipeline v0.5.0 + ship-readiness review
Installs the three-layer agent-pipeline scaffold (https://github.com/varutasu/agent-pipeline @ v0.5.0):

L1 — Context (curated brain)
- AGENTS.md: orientation, conventions, 8 explicit gotchas
- .cursor/rules/: no-go-zones, api-routes, auth-and-permissions,
  db-and-schema, ui-and-theming, schema-map
- .cursor/skills/: add-api-route, add-page recipes
- docs/agent-context/README.md: layer explainer
- docs/SCHEMA_MAP.md: hand-curated Neon Postgres reference
  (replaces Prisma schema map since stack is raw SQL)

L2 — Subagent roles (copied verbatim from upstream templates)
- 9 .cursor/agents/role-*.md files: Conductor, IA-Architect,
  UX-Reviewer, Architect, Implementer, Reviewer,
  Design-System-Auditor, A11y-Auditor, Doc-Writer

L3 — Pipeline scaffolding (Vercel variant)
- CI: lint + schema-map-drift only (no duplicate build —
  Vercel handles it). Test job commented out until vitest lands.
- preview-smoke + visual-diff via wait-for-vercel-preview
- pr-health-rollup sticky comment aggregator
- agent-context-drift weekly cron
- PULL_REQUEST_TEMPLATE, CODEOWNERS (auth/admin paths tagged)
- .convoys/ folder + seed ship-readiness.md review
- lib/flags/index.js (JS — converted from TS template)
- scripts/wt.sh (Cursor 3.2 deprecation stub),
  scripts/log-convoy-event.sh
- tests/smoke/app.smoke.spec.ts (Playwright skeleton)

Manifest
- .agent-context-manifest.yml: tracks 31 artifacts by sha256
  for future sync-agent-context drift detection

Review
- .convoys/ship-readiness.md: 16 findings (7 P0 ship-blockers,
  5 P1 quality-bar, 4 P2 refactor, P3 UX/IA/a11y/docs) with
  proposed 13-convoy launch sequence.

No production code changed in this commit. All findings in
the ship-readiness review will be addressed in follow-up convoys
starting with fix-auth-bypass.

Structural brain: user-code-review-graph MCP has indexed the
codebase (122 files, 628 nodes, 5602 edges, 11 communities,
84 flows). Per-developer; not committed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 23:16:08 -05:00

3.7 KiB

name description
add-api-route Add a new authenticated API route under pages/api/. Use when you need to expose a new server endpoint to the client, scaffold an admin-only route, or add a CRUD method to an existing resource. Walks through file placement, auth, validation, DB access, and error handling for the tcg-vault stack.

Add an API route

pages/api/<path>.js becomes /api/<path>. Dynamic segments use [name] folder/file naming.

Step 1: Decide the path

Pattern Example Notes
Resource collection pages/api/decks.js/api/decks GET list, POST create
Single resource pages/api/decks/[id].js/api/decks/:id GET, PUT, DELETE
Sub-resource pages/api/decks/[id]/cards.js GET, POST
Action pages/api/cards/find-or-create.js POST, RPC-style

Step 2: Pick the auth pattern

Use case Wrapper
Generic logged-in user getUserFromRequest(req) inline
Collection-scoped op withCollectionPermission('viewer'|'editor'|'owner')
Admin-only inline if (user.role !== 'admin') return res.status(403)

Step 3: Skeleton

import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../lib/permission-middleware';

export default async function handler(req, res) {
  // 1. Method gate
  if (!['GET', 'POST'].includes(req.method)) {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    // 2. Auth
    const user = await getUserFromRequest(req);
    if (!user || !req.headers.authorization) {
      // Guard against the known dev-fallback bug; require real Bearer token.
      return res.status(401).json({ error: 'Authentication required' });
    }

    if (req.method === 'GET') {
      const { rows } = await sql`
        SELECT id, name FROM example_table WHERE user_id = ${user.userId}
      `;
      return res.status(200).json({ items: rows });
    }

    // 3. Validate body
    const { name } = req.body || {};
    if (!name || typeof name !== 'string' || name.trim().length === 0) {
      return res.status(400).json({ error: 'name is required' });
    }

    // 4. Mutation
    const { rows } = await sql`
      INSERT INTO example_table (user_id, name)
      VALUES (${user.userId}, ${name.trim()})
      RETURNING id, name
    `;

    return res.status(201).json({ item: rows[0] });
  } catch (err) {
    console.error('[example handler]', err);
    return res.status(500).json({ error: 'Internal server error' });
  }
}

Step 4: Wire the client

Use fetch with the auth header pattern from existing pages:

const token = localStorage.getItem('auth_token');
const res = await fetch('/api/example', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  },
  body: JSON.stringify({ name }),
});

Step 5: Check

  • Method gate is the first thing in the handler.
  • Auth check requires both getUserFromRequest AND req.headers.authorization (until the middleware bug is fixed).
  • All inputs validated.
  • Tagged-template SQL only (no db.query(...)).
  • try/catch wraps the whole body.
  • If the route mutates a collection: call logCollectionActivity.
  • Add a Convoy entry if the route is new functionality (vs. a bug fix).

Anti-patterns

Don't Do
db.query(\SELECT … ${userInput}`)` await sql\SELECT … ${userInput}``
Forget the method gate Always declare which methods are allowed
Return res.json(err.message) in catch Generic message; log details server-side
SELECT * from cards Project narrow columns
Add another /api/test-* endpoint Use a real test runner once one's adopted