---
name: server-functions
description: "Use when adding or changing server-side code in app: server functions (createServerFn) that select or write data, their middleware, global request middleware (src/start.ts), validation, transactions and error messages, on-demand subset selects, REST/API routes, background-job endpoints, or deciding what client code may import from src/server."
metadata:
  type: convention
  library: wcz-layout
---

Mechanics (`createServerFn`, `.validator`, `createMiddleware`, server routes, `createHandlers`):
load `@tanstack/start-client-core#start-core` with its `server-functions`, `middleware` and
`server-routes` sub-skills. Our RPC entrypoints stay in `actions/<entity>.ts`, not
`*.functions.ts`; server-only helper protection still applies.

## Rules

- Default to internal server functions in `src/server/actions/<entity>.ts`. Build REST routes
  (`src/routes/api/<entities>/`) only for a requested public API. Ask which permission guards
  the functions when the task does not say.
- Every server function has `authMiddleware()` (any signed-in user) or
  `authMiddleware("<key>")`, after `databaseMiddleware()` when it touches the database. Route
  guards only hide pages; a server function is a public endpoint. Omit authentication only
  for an intentionally public operation.
- Middleware arrays run in order; later entries override overlapping context properties:
  `databaseMiddleware()` → `authMiddleware(key)` → `validationMiddleware(schema)` (REST only;
  server functions use `.validator()`). `databaseMiddleware` brings `user: User | null` and
  `authMiddleware` narrows it to `User`; auth before validation keeps validation errors from
  anonymous callers.
- Start checks server functions for CSRF by default, but a `createStart` in `src/start.ts`
  replaces that default: an app that adds the file (global middleware) puts `csrfMiddleware`
  from `wcz-layout/middleware` first in `requestMiddleware`, never a hand-made origin check.
- Builders read `.validator(schema)` → `.middleware([...])` → `.handler()`. Every input has a
  schema from `src/lib/schemas/` (a list of ids: `z.array(z.uuid())`).
- `databaseMiddleware` is app-local (`src/server/middleware/`, in the template): one
  transaction per call as `context.db`, the acting user stamped for the audit trigger, and
  Postgres errors rethrown as `Error(detail)`. Never open another transaction or import `db` in
  a handler. Fail with `throw new Error(message)`; the client shows the message in `alert()`.
- Selects return rows of the collection's schema. Writes return nothing, the client refetches.
  Inserts end with `.onConflictDoNothing({ target: table.id })`, so a replayed create is a
  no-op.
- The select behind an on-demand collection is POST (a lazy join asks for `id IN (…)`, and a GET
  URL with a thousand ids fails with 431), validates `createQuerySchema<Entity>()` from
  `agnostic-query/zod` and returns `toDrizzle(context.db, table, data)` from
  `agnostic-query/drizzle/pg` (example; more in `agnostic-query#adapters`). The type argument
  types the rows: without it the collection's `queryFn` fails to type-check.
- Client and isomorphic code import from `src/server/` only server functions (`actions/`) and
  table definitions (`db/schemas/`, for `createSelectSchema`). Import protection guards only
  `*.server.*` filenames, so nothing else stops a wrong import. Logic shared by several handlers
  goes in `src/server/<entity>.ts`, imported by actions only.
- Background jobs are API routes with exactly `[databaseMiddleware(), authMiddleware()]`:
  Kubernetes cron calls them with an app token. Add no other security layer, even though any
  signed-in user could trigger the job.

## Examples

```ts
// src/server/actions/feature.ts
import { createServerFn } from "@tanstack/react-start";
import { eq, inArray } from "drizzle-orm";
import { authMiddleware } from "wcz-layout/middleware";
import z from "zod";
import { FeatureSchema } from "~/lib/schemas/feature";
import { featureTable } from "../db/schemas/feature";
import { databaseMiddleware } from "../middleware/databaseMiddleware";

export const selectFeatures = createServerFn()
  .middleware([databaseMiddleware(), authMiddleware("admin")])
  .handler(({ context }) => context.db.select().from(featureTable));

export const insertFeature = createServerFn({ method: "POST" })
  .validator(FeatureSchema)
  .middleware([databaseMiddleware(), authMiddleware("admin")])
  .handler(async ({ data, context }) => {
    await context.db
      .insert(featureTable)
      .values(data)
      .onConflictDoNothing({ target: featureTable.id });
  });

export const updateFeature = createServerFn({ method: "POST" })
  .validator(FeatureSchema)
  .middleware([databaseMiddleware(), authMiddleware("admin")])
  .handler(async ({ data, context }) => {
    await context.db.update(featureTable).set(data).where(eq(featureTable.id, data.id));
  });

export const deleteFeatures = createServerFn({ method: "POST" })
  .validator(z.array(z.uuid()))
  .middleware([databaseMiddleware(), authMiddleware("admin")])
  .handler(async ({ data, context }) => {
    await context.db.delete(featureTable).where(inArray(featureTable.id, data));
  });
```

```ts
// on-demand select (its collection: client-db, Sync mode)
import { toDrizzle } from "agnostic-query/drizzle/pg";
import { createQuerySchema } from "agnostic-query/zod";
import type { Feature } from "~/lib/schemas/feature";

export const selectFeatures = createServerFn({ method: "POST" })
  .validator(createQuerySchema<Feature>())
  .middleware([databaseMiddleware(), authMiddleware("admin")])
  .handler(({ data, context }) => toDrizzle(context.db, featureTable, data));
```

```ts
// src/routes/api/features/index.ts
import { createFileRoute } from "@tanstack/react-router";
import { authMiddleware, validationMiddleware } from "wcz-layout/middleware";
import { FeatureSchema } from "~/lib/schemas/feature";
import { featureTable } from "~/server/db/schemas/feature";
import { databaseMiddleware } from "~/server/middleware/databaseMiddleware";

export const Route = createFileRoute("/api/features/")({
  server: {
    handlers: ({ createHandlers }) =>
      createHandlers({
        GET: {
          middleware: [databaseMiddleware(), authMiddleware("admin")],
          handler: async ({ context }) =>
            Response.json(await context.db.select().from(featureTable)),
        },
        POST: {
          middleware: [
            databaseMiddleware(),
            authMiddleware("admin"),
            validationMiddleware(FeatureSchema),
          ],
          handler: async ({ context }) => {
            const [created] = await context.db
              .insert(featureTable)
              .values(context.data)
              .returning();
            return Response.json(created, { status: 201 });
          },
        },
      }),
  },
});
```
