Skip to main content
This guide shows how to write feature code the way the kit’s core is written: commands that change data, queries that read it, Zod contracts shared by the browser and the server, and components that call commands. Each rule comes with the reason behind it and what enforces it. For a full feature built step by step, see Build a feature.

How the pieces fit

Reads go through the page: page.tsx checks access, calls a query and passes the data to a component. Writes start in the component: it calls a command through run, the command validates input, checks session, permissions and service mode, writes and returns a result, and the component refreshes the page so the query runs again.

Commands

A command is a server action in services/commands/ that changes data. Every export of a "use server" file is a public POST endpoint that anyone can call without going through your UI, so the command must check everything itself.

The contract

  1. The file starts with "use server" and exports only the command. Helpers stay unexported so the browser can’t call them, and the architecture test checks every export.
  2. Signature (input: unknown, confirmation?: unknown). TypeScript types don’t exist in a request from the browser. unknown tells the truth and forces you to validate before reading fields. confirmation is separate because run attaches it in service mode.
  3. Input is validated with a Zod schema from contracts/ (safeParse), the same schema the form uses.
  4. Organization and permissions come from a guard: requireModuleAccess(key) or getOrgContext(). Take organizationId from the context, never from input.
  5. Call assertServiceModeConfirmed(context, confirmation) right after the context, before the first Prisma call. See Service mode.
  6. Wrap the body in try and pass errors to handleCommandError(error, "<message>"). The component always gets { success, data?, error? }, never a raw server exception.

Step order for a new command

src/features/invoices/services/commands/create-invoice-command.ts
  1. "use server"; on the first line.
  2. (input: unknown, confirmation?: unknown), returning Promise<OperationResult<T>>.
  3. The whole body in try { … } catch (error) { return handleCommandError(error, "…"); }.
  4. Validate with safeParse; on failure, return { success: false, error }.
  5. const context = await requireModuleAccess("<key>"), where <key> is the key from the feature’s module.ts. This gives the command the same access decision as the page, so nobody can bypass the module’s role rules by posting directly.
  6. Immediately assertServiceModeConfirmed(context, confirmation), passing the parameter unchanged.
  7. Any rule narrower than page access, based on context.orgRole or context.userRole.
  8. Prisma with organizationId: context.organizationId: in where for reads, updates and deletes, in data for creates.
  9. revalidatePath(...) and return { success: true, data }.
Use getOrgContext() instead of requireModuleAccess() only when the feature has no module definition, or the command’s access rule doesn’t depend on it.
Read roles from the context (context.userRole, context.orgRole). Helpers in src/shared/lib/auth/helpers.ts such as getAdminUserOrNull() read the global role from a cookie cache that can be up to 5 minutes old.

A command from the core

inviteUserCommand is the core’s reference command. It uses a separate global-admin guard because only global admins may create accounts, even though org owners can open the same page with MULTI_ORG=true:
src/features/users/services/commands/invite-user-command.ts
The core’s command messages are currently hardcoded in Polish, and components display result.error as is. Form validation errors are shown from translated strings before anything is sent, so users rarely see server validation messages. Write your own command messages in the language your app needs.

Results and errors

OperationResult<T> from src/shared/types/common.ts:
src/shared/types/common.ts
It’s not a discriminated union: after checking result.success, data is still optional. Add extra fields with an intersection, like & { warning?: "mail-failed" } above. handleCommandError turns exceptions into results:
src/shared/utils/error-handling.ts
Technical error text (for example from Prisma) never reaches the browser; details stay in the log. Return expected business errors with return; use throw new DomainError("…") from helpers where returning is awkward. Give custom error classes a string name (name = "MyError"), because minification mangles class names in production logs. ESLint enforces this for classes extending Error directly.

Server actions outside the contract

Actions that change something other than organization data (your own password, the session’s active organization, a log entry) have their own signatures. They still call a session guard before Prisma, validate input and return OperationResult. Functions in services/commands/ without "use server" (such as joinOrganizationCommand) aren’t server actions, just internal functions called from server code.

Queries

A query reads data for a page. Rules:
  • Lives in services/queries/, without "use server". Queries are called by server code. The directive would make them public POST endpoints, and an org-context action would then need service-mode confirmation just to read.
  • First line import "server-only";. Importing the file from a client component then fails the build instead of pulling Prisma into the browser bundle.
  • Session guard before Prisma. An organization-data query starts with getOrgContext() and filters by organizationId. The page already called requireModuleAccess(), but the query has its own guard because another page could import it, and the architecture test requires it.
  • Result type in contracts/*.types.ts, so the component receiving the props imports the same type.
  • Export only queries from the file. An exported helper without a guard fails the architecture test.
src/features/invoices/services/queries/invoice-queries.ts
getOrgContext() never returns an empty result: without a session it redirects, without an organization it throws. A real example from the core is getOrganizationMembersQuery in Organizations.

Contracts

contracts/ holds what both the browser and the server need:
  • *.schemas.ts: Zod schemas and their z.infer types. The form validates with the schema in the browser and the command validates with it on the server, so the input rule lives in one place.
  • *.types.ts: types of data that queries return and components receive.
Client components import these files, so they must not import server code (Prisma, next/headers, server-only).
src/features/users/contracts/user-account.schemas.ts
The schema also normalizes: trim and toLowerCase keep emails in one form, and default fills in the role. The kit uses Zod 4 (for example z.email()).

Calling commands from the UI

Components call organization-data commands through run from useServiceModeAction(), not directly:
src/features/users/components/invite-user-dialog.tsx
  • Import the command directly from its "use server" file. Next.js turns the call into a POST request.
  • run(command, input), not command(input). Outside service mode run calls the command immediately. In service mode it shows the confirmation dialog first. A direct call sends no confirmation, so in service mode it always fails, and no test catches that.
  • Render serviceModeAction.dialog and handle null (the user cancelled). Don’t show an error and don’t write your own dialog.
  • On success: false, show result.error with a translated fallback.
  • On success: true, show a message, close the form and call router.refresh() (from @/i18n/routing) so the page’s query runs again.
  • Forms use react-hook-form with zodResolver and the schema from contracts/. When the schema has defaults or transforms, pass three type parameters: useForm<z.input<…>, unknown, z.infer<…>>.
  • Non-action calls such as fetch to an API route use requestConfirmation() from the same hook. The route must verify the confirmation like a command does.
  • authClient.organization.* calls don’t go through run and don’t know about service mode. Changes a superadmin must be able to make in service mode go through a kit command.

Never change data while rendering

page.tsx and layout.tsx render on GET requests. Don’t write data there:
  1. A change in a GET request is open to CSRF: a link on another site or in an email triggers it with the user’s session cookie (better-auth sets it SameSite=Lax). Server actions only accept POST, and Next.js rejects requests whose Origin doesn’t match Host.
  2. Rendering can’t ask a superadmin for confirmation, so service mode is bypassed.
  3. The architecture test checks "use server" files and queries, not pages.
Instead, render a client component whose button or form calls a command through run, then router.refresh() or router.push().

Style rules

ESLint runs in npm run lint (part of npm run verify and CI) and as eslint --fix on commit. Use // WHY: for reasons the code can’t show; prefer a descriptive name (INVITATION_TTL_MS, sendWelcomeEmailBestEffort) over a comment that explains what code does.

The architecture test

src/__tests__/server-entrypoints-guard.test.ts parses your TypeScript and checks that server entry points call their guards in the right order. It runs in npm test, so also in npm run verify and CI. It exists because a missing guard call is a security hole that mutation testing can’t catch: there’s nothing to mutate. Which files. TypeScript files under src/ (excluding __tests__ and generated) whose first statement is "use server", plus every file whose path contains /services/queries/. Every exported function in them is checked. Rule 1: session guard first. The first access in the function must be a call to one of:
src/__tests__/server-entrypoints-guard.test.ts
Guards count under an import alias, through a top-level constant, and through a function declared at the top level of the same file. Prisma means the prisma identifier and anything imported from @/shared/lib/prisma. An exported function without a guard fails even if it doesn’t use Prisma. Rule 2: service-mode confirmation. In "use server" files only: a function that calls getOrgContext or requireModuleAccess must call assertServiceModeConfirmed before its first Prisma use, even if it only reads, and even if it uses no Prisma at all. The second argument must be the function’s own parameter (or a helper’s parameter that received it unchanged), with no default value and never reassigned.

Fixing a red test

The test reports violations as <path>#<function name>.

Exceptions

Exceptions to rule 1 go in the UNGUARDED_ALLOWED map at the top of the test, keyed by <path>#<function> with a justification. The kit has one:
src/__tests__/server-entrypoints-guard.test.ts
The better-auth hook calls it before the session exists, so there’s no session to check. An exception makes sense only for functions like this: called exclusively from server code where no session exists yet. Rule 2 has no exceptions.
The analysis is syntactic. It catches mistakes, not deliberate workarounds: it doesn’t see a "use server" action defined inside another function, or Prisma called through a service in another file. It also checks that a guard is called, not that queries filter by organizationId. That’s what the runtime guard and isolation tests are for.