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. Prefer a permission checked with can(context, "<module>.<permission>") over comparing context.orgRole in the command, so a project can change the roles in src/gato.config.ts.
  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. 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.
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

GatoJS’s own commands on organization data are built with defineCommand 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
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. New actions of this kind should still call a session guard before Prisma, validate input and return OperationResult. 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 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.

Module entry points

A module disabled with enabled: 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) returns true for auth and organizations always, and for any other key only when the module is in the registry after src/gato.config.ts is applied. An unknown or disabled key gives false. A route calls it as its first statement and answers 404 with no body when it is false, before checking an API key or a session.
  • requireModuleEnabled(key) throws ModuleDisabledError instead. A command calls it as the first statement in try, and handleCommandError turns 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, POST and the rest) of every route.ts under src/app/;
  • every export of a "use server" file in src/features/<x>/ (except auth and organizations, which can’t be disabled), and of a "use server" file in src/app/ or src/shared/ that belongs to a module other than core.
The module of a file is <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.
Every route.ts needs a module. A route that no module’s files covers, such as a route of your feature outside its projectModules patterns, has no key a guard could use, and the test reports it. Add the route’s folder to your project module’s files (for example "src/app/api/invoices/**").
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 requireModuleAccess imported from @/shared/lib/auth/require-module-access, or requireModuleEnabled or isModuleEnabled imported 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 const initialized with that literal; a guard with another module’s key fails;
  • for isModuleEnabled, has the form if (!isModuleEnabled("<key>")) … with a branch that ends in return or throw; in a helper function only throw counts, because return ends the helper, not the entry point;
  • is not inside a nested function (a callback, an arrow function, a method);
  • is not inside a try whose catch swallows the error: the catch must end with throw or return handleCommandError(…);
  • for requireModuleAccess, which is async, sits directly after await (await requireModuleAccess(…), const context = await …, return await …). A call of a local async helper that guards counts the same way only after await.
Prisma on a path the code takes when the guard fires counts as Prisma before the guard: in the 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.
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 a catch or finally block counts as always called. Order is syntactic, without control flow.
  • await counts only as the direct parent of the call: await (requireModuleAccess(…)) and return requireModuleAccess(…) from an async function are violations. Write return await.
  • A helper without async that returns the promise of a guard never counts as a guard, even with await check().
  • catch is judged by its last statement only, and handleCommandError by its name and import path.
  • if (!isModuleEnabled(…)) return … passes whatever it returns.
  • A key built any other way than a literal or a const with 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, handleCommandError or the key constant counts as the original.
  • Inline "use server" actions, "use server" files outside src/app/, src/features/ and src/shared/, and core files in src/shared/ are not scanned.
  • Pages (page.tsx) and layouts are not entry points of this test; requireModuleAccess(key) in the page protects them.