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 inservices/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
- 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. - Signature
(input: unknown, confirmation?: unknown). TypeScript types don’t exist in a request from the browser.unknowntells the truth and forces you to validate before reading fields.confirmationis separate becauserunattaches it in service mode. - Input is validated with a Zod schema from
contracts/(safeParse), the same schema the form uses. - Organization and permissions come from a guard:
requireModuleAccess(key)orgetOrgContext(). TakeorganizationIdfrom the context, never frominput. - Call
assertServiceModeConfirmed(context, confirmation)right after the context, before the first Prisma call. See Service mode. - Wrap the body in
tryand pass errors tohandleCommandError(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
"use server";on the first line.(input: unknown, confirmation?: unknown), returningPromise<OperationResult<T>>.- The whole body in
try { … } catch (error) { return handleCommandError(error, "…"); }. - Validate with
safeParse; on failure, return{ success: false, error }. const context = await requireModuleAccess("<key>"), where<key>is the key from the feature’smodule.ts. This gives the command the same access decision as the page, so nobody can bypass the module’s role rules by posting directly.- Immediately
assertServiceModeConfirmed(context, confirmation), passing the parameter unchanged. - Any rule narrower than page access, based on
context.orgRoleorcontext.userRole. - Prisma with
organizationId: context.organizationId: inwherefor reads, updates and deletes, indatafor creates. revalidatePath(...)andreturn { success: true, data }.
getOrgContext() instead of requireModuleAccess() only when the feature has no module definition, or the command’s access rule doesn’t depend on it.
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
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 returnOperationResult. 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 publicPOSTendpoints, 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 byorganizationId. The page already calledrequireModuleAccess(), 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 theirz.infertypes. 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.
next/headers, server-only).
src/features/users/contracts/user-account.schemas.ts
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 throughrun 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 aPOSTrequest. run(command, input), notcommand(input). Outside service moderuncalls 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.dialogand handlenull(the user cancelled). Don’t show an error and don’t write your own dialog. - On
success: false, showresult.errorwith a translated fallback. - On
success: true, show a message, close the form and callrouter.refresh()(from@/i18n/routing) so the page’s query runs again. - Forms use react-hook-form with
zodResolverand the schema fromcontracts/. When the schema has defaults or transforms, pass three type parameters:useForm<z.input<…>, unknown, z.infer<…>>. - Non-action calls such as
fetchto an API route userequestConfirmation()from the same hook. The route must verify the confirmation like a command does. authClient.organization.*calls don’t go throughrunand 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:
- 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 acceptPOST, and Next.js rejects requests whoseOrigindoesn’t matchHost. - Rendering can’t ask a superadmin for confirmation, so service mode is bypassed.
- The architecture test checks
"use server"files and queries, not pages.
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
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 theUNGUARDED_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