/factory-kit:factory-api-route-engineerfrom factory-kit
Designs and implements API endpoints following factory conventions: server actions, tRPC procedures, or REST routes. Handles pagination, multi-field search, aggregated stats, mutation lifecycle hooks, and custom error taxonomy.
Ships in factory-kit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Apply the api-route-engineer specialist workflow. Build endpoints grounded in the factory's API conventions, not bespoke per-route handlers. Load the canonical factory-api and factory-auth skills through the host's skill capability when needed.
API style? Apply the decision matrix from factory-api.md:
If the project already commits to one, use it. Don't mix.
What's the surface?
Auth tier?
Input shape? Per-endpoint Zod schema. For paginated lists:
limit: number().int().min(1).max(100).default(50)offset: number().int().min(0).default(0)orderBy: enum([...]).default('createdAt')orderDir: enum(['asc','desc']).default('desc')Output shape? Three options:
{ items: T[], total?: number } — include total if pagination needs itT | null — return null on not-found, throw NotFoundError if the caller expected itActionResult<T> for server actionsMulti-tenant filter? Every query / mutation in orgProcedure filters by ctx.orgId. This is automatic enforcement, not "remember to add WHERE."
Pagination shape?
Aggregations in list? If the list view needs counts (e.g. "customer with vehicle count"), use a subquery / leftJoin + groupBy rather than a per-row round-trip:
ctx.db.select({
...getTableColumns(customers),
vehicleCount: count(vehicles.id),
}).from(customers).leftJoin(vehicles, ...).groupBy(customers.id);
Error shape?
AuthError, NotFoundError, ValidationError from src/lib/errors.ts{ error: 'message' }TRPCError({ code, message })Audit log? Fire-and-forget at the mutation boundary. Never await it on the critical path. See factory-security.md.
// features/customers/actions.ts
'use server';
import { customerInputSchema } from './schema';
import { withOrgContext } from '@/lib/auth';
import { db } from '@/db';
import { customers } from '@/db/schema';
import { logAdminAction } from '@/lib/admin/activity';
import type { ActionResult } from '@/lib/api/types';
export async function createCustomer(input: unknown): Promise<ActionResult<Customer>> {
const parsed = customerInputSchema.safeParse(input);
if (!parsed.success) return { error: parsed.error.issues[0].message };
return withOrgContext(async ({ orgId, user }) => {
const [customer] = await db.insert(customers).values({
...parsed.data,
orgId,
}).returning();
logAdminAction({ action: 'customer.create', subject_id: customer.id, actor_id: user.id })
.catch((err) => console.error('audit log failed', err));
return { data: customer };
});
}
// server/api/routers/customers.ts
import { z } from 'zod';
import { eq, and, ilike, or, count, desc, asc } from 'drizzle-orm';
import { createTRPCRouter, orgProcedure } from '../trpc';
import { customers, vehicles } from '@/db/schema';
const listInput = z.object({
limit: z.number().int().min(1).max(100).default(50),
offset: z.number().int().min(0).default(0),
orderBy: z.enum(['createdAt', 'name']).default('createdAt'),
orderDir: z.enum(['asc', 'desc']).default('desc'),
q: z.string().optional(),
});
export const customersRouter = createTRPCRouter({
list: orgProcedure.input(listInput).query(async ({ ctx, input }) => {
const conditions = [eq(customers.orgId, ctx.orgId)];
if (input.q) {
const term = `%${input.q}%`;
conditions.push(or(ilike(customers.name, term), ilike(customers.email, term))!);
}
return ctx.db.select().from(customers)
.where(and(...conditions))
.limit(input.limit)
.offset(input.offset)
.orderBy(input.orderDir === 'desc' ? desc(customers[input.orderBy]) : asc(customers[input.orderBy]));
}),
create: orgProcedure.input(createInput).mutation(async ({ ctx, input }) => {
const [customer] = await ctx.db.insert(customers).values({ ...input, orgId: ctx.orgId }).returning();
logAdminAction({ action: 'customer.create', subject_id: customer.id, actor_id: ctx.user.id })
.catch((err) => console.error('audit log failed', err));
return customer;
}),
});
// server/api/root.ts
export const appRouter = createTRPCRouter({
customers: customersRouter,
// ... add a line per domain. Manual registration, easy to grep.
});
## Restated request
<one sentence>
## API surface
- Style: <server actions / tRPC / REST>
- Auth tier: <public / protected / org>
- Operations: <list / detail / create / update / delete / custom>
## Files to create or modify
<bulleted with paths>
## Code
<organized by file>
## Conventions check
- Per-endpoint Zod input: yes
- Multi-tenant filter (orgId): yes
- Pagination shape: <offset / cursor — why>
- Aggregation strategy: <subquery / leftJoin / N+1 — flag if N+1>
- Audit log fire-and-forget: <yes — at mutation boundary>
- Error class taxonomy used: <yes>
## Open questions
<things the user should confirm>
UPDATE or DELETE without WHERE. ESLint Drizzle rule from factory-data-layer.md.publicProcedure. Auth tier explicitly per endpoint.Error objects to the client. Convert at the boundary.orgId from the request body. Always from session.If the user asks to add a single field to an existing input schema or change one validation rule, do it directly. The framework is for new endpoints, new routers, or substantial API surface changes.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
tRPC, Zod, TypeScript, REST API, Next.js
api-design, trpc, server-actions, rest-api, zod-schemas, pagination
npx claudepluginhub nonlinear-xyz/factory-kit --plugin factory-kit47 skills in this plugin
/factory-animationMotion discipline distilled across builds. Attention as a fixed per-viewport budget, figure/ground separation (calm the ground, load motion into the figure), one focal point of motion per screen, diegetic-over-decorative test, trigger-on-intent-then-settle over perpetual loops, and the prefers-reduced-motion fallback. Recipe pairs Astro with a Remotion video kit (rendered assets in public/). Read whenever you add motion to a marketing surface or any page where movement competes with reading. Paired with factory-design, which owns the static visual vocabulary motion sits on top of./factory-apiAPI conventions for both server actions and tRPC builds. Covers the decision between them, per-mutation Zod input schemas, central router composition, pagination shape, multi-field search via Drizzle `ilike` + `or()`, mutation lifecycle hooks, conditional query enabling, stale-time defaults, error response shape and custom error class taxonomy, mutation-boundary audit logging, fetch adapter for tRPC routes. Read when designing or implementing any data-mutation endpoint./factory-authAuth and authorization conventions distilled across builds with three different auth stacks (Better Auth + orgs, Supabase Auth + RLS, Clerk). Covers the provider decision matrix, the unified wrapper interface (`requireAuth` / `requireRole` / `withOrgContext`), procedure tier stacking, session handling, OAuth callback safety, plugin composition with Better Auth, and the anti-patterns (hardcoded allowlists, admin client at module scope, triple-fallback auth surfaces).Other plugins' skills for the same job