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. Prefer a permission checked with
can(context, "<module>.<permission>")over comparingcontext.orgRolein the command, so a project can change the roles insrc/gato.config.ts. - 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 of a registered module (one with module.ts in the registry) that skips requireModuleAccess still checks that its module is enabled: call requireModuleEnabled("<key>") as the first statement in try (Module entry points). Don’t add that guard for a feature without module.ts: its key is not in the registry, so the guard would fail every call. Register the module first.
A command from the core
GatoJS’s own commands on organization data are built withdefineCommand and run by runCommand, which performs the steps of the contract above in a fixed order and lets other modules add before hooks. inviteUserCommand is the users.invite command. Only global admins may create accounts, even though organization owners can open the same page with MULTI_ORG=true, so its access is "global-admin":
src/features/users/services/commands/invite-user-command.ts
runCommand checks that users is enabled, requires a global admin, checks the service mode confirmation, validates the input, runs other modules’ hooks and validates again, then calls run and emits users.invited only after run succeeded. Your project commands can follow the same pattern, or keep the manual steps listed in Step order for a new command.
The core’s command messages are user-facing and currently hardcoded in Polish (localization is planned): above,
Brak uprawnień means “Permission denied”, Nieprawidłowe dane “Invalid data” and Nie udało się zaprosić użytkownika “Could not invite the user”. 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. New actions of this kind should still call a session guard before Prisma, validate input and returnOperationResult. The kit’s own changePasswordCommand is an exception: it checks the session, but does not validate input on the server and returns its own result type (see Known limitations). 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
Module entry points
A module disabled withenabled: false in src/gato.config.ts leaves the registry, so requireModuleAccess answers 404 for it. An API route or a command that doesn’t call requireModuleAccess checks its module itself, with the functions from src/shared/lib/modules/require-module-enabled.ts:
isModuleEnabled(key)returnstrueforauthandorganizationsalways, and for any other key only when the module is in the registry aftersrc/gato.config.tsis applied. An unknown or disabled key givesfalse. A route calls it as its first statement and answers 404 with no body when it isfalse, before checking an API key or a session.requireModuleEnabled(key)throwsModuleDisabledErrorinstead. A command calls it as the first statement intry, andhandleCommandErrorturns the error into the command’s default message and logs it as a warning, not an error.
src/app/api/invoices/route.ts
src/features/invoices/services/commands/send-invoice-command.ts
The entry point test
src/__tests__/architecture/module-entry-points-check-enabled.test.ts runs in npm test and checks that every module entry point starts with its own module’s guard. Entry points are:
- the exported HTTP methods (
GET,POSTand the rest) of everyroute.tsundersrc/app/; - every export of a
"use server"file insrc/features/<x>/(exceptauthandorganizations, which can’t be disabled), and of a"use server"file insrc/app/orsrc/shared/that belongs to a module other thancore.
<x> for src/features/<x>/. For other paths it is the module whose files pattern in .wa/kit.json (modules or projectModules) matches the path, ignoring core.
An entry point passes when its first event is a valid guard call, before the first Prisma access (the prisma identifier or a name imported from @/shared/lib/prisma). A call of a function from the same file counts as the first event of that function’s body. A valid guard call:
- is
requireModuleAccessimported from@/shared/lib/auth/require-module-access, orrequireModuleEnabledorisModuleEnabledimported from@/shared/lib/modules/require-module-enabled(an import alias is fine); a function with the same name from another path doesn’t count; - passes the key of the file’s own module as a string literal, or as a top-level
constinitialized with that literal; a guard with another module’s key fails; - for
isModuleEnabled, has the formif (!isModuleEnabled("<key>")) …with a branch that ends inreturnorthrow; in a helper function onlythrowcounts, becausereturnends the helper, not the entry point; - is not inside a nested function (a callback, an arrow function, a method);
- is not inside a
trywhosecatchswallows the error: thecatchmust end withthroworreturn handleCommandError(…); - for
requireModuleAccess, which isasync, sits directly afterawait(await requireModuleAccess(…),const context = await …,return await …). A call of a localasynchelper that guards counts the same way only afterawait.
if (!isModuleEnabled(…)) branch, and in the catch or finally of a try that contains the guard.
Violations are reported as <path>#<name>. Exceptions go in the ALLOWED map in the test, each with a reason. The kit lists the healthcheck route, the better-auth handler and two users commands that log impersonation. An entry that no longer names an entry point fails the test.
Limits of the analysis
Limits of the analysis
The analysis is syntactic, like the server entry point test. It catches mistakes, not deliberate workarounds:
- A guard in a function from another file (a service, a shared helper) is invisible, and Prisma called through such a service doesn’t count as an event. Order is checked only against Prisma in the same file.
- Prisma in a nested function defined before the guard, and Prisma under another name (such as a transaction client passed as a parameter), don’t count.
- A guard in a conditional branch (
if,switch,?:,&&) or in acatchorfinallyblock counts as always called. Order is syntactic, without control flow. awaitcounts only as the direct parent of the call:await (requireModuleAccess(…))andreturn requireModuleAccess(…)from anasyncfunction are violations. Writereturn await.- A helper without
asyncthat returns the promise of a guard never counts as a guard, even withawait check(). catchis judged by its last statement only, andhandleCommandErrorby its name and import path.if (!isModuleEnabled(…)) return …passes whatever it returns.- A key built any other way than a literal or a
constwith a literal (a template, an import, a parameter) is a violation, even when it’s right. - Only top-level functions of the file count as helpers.
- A variable or parameter that shadows an imported guard,
handleCommandErroror the key constant counts as the original. - Inline
"use server"actions,"use server"files outsidesrc/app/,src/features/andsrc/shared/, and core files insrc/shared/are not scanned. - Pages (
page.tsx) and layouts are not entry points of this test;requireModuleAccess(key)in the page protects them.