> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code patterns

> How to write GatoJS commands, queries and Zod contracts, call them from the UI with service-mode confirmation, and keep the server entry-point architecture test green.

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](https://docs.gatojs.com/guides/build-a-feature.md).

## How the pieces fit

```mermaid theme={null}
flowchart LR
    subgraph server["Server"]
        page["page.tsx<br/>requireModuleAccess(key)"]
        query["services/queries/<br/>query"]
        command["services/commands/<br/>'use server' command"]
    end
    subgraph browser["Browser"]
        component["components/<br/>'use client' component"]
    end
    contracts["contracts/<br/>Zod schemas and types"]
    db[("Postgres")]
    page -->|"calls"| query
    query -->|"Prisma + organizationId"| db
    page -->|"data as props"| component
    component -->|"run(command, input) → POST"| command
    command -->|"Prisma + organizationId"| db
    contracts -.->|"form schema"| component
    contracts -.->|"safeParse"| command
    contracts -.->|"result type"| query
```

**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.

| Part | Location | Called by | Session check | Returns |
| - | - | - | - | - |
| Page | `src/app/[locale]/(app)/<x>/page.tsx` | Next.js on GET | `requireModuleAccess(key)` | JSX |
| Query | `src/features/<x>/services/queries/*.ts` | Page or other server code | Session guard, usually `getOrgContext()` | Data |
| Command | `src/features/<x>/services/commands/*.ts` with `"use server"` | Component via `run` | `requireModuleAccess(key)` or `getOrgContext()`, then `assertServiceModeConfirmed` | `OperationResult<T>` |
| Contract | `src/features/<x>/contracts/*.schemas.ts`, `*.types.ts` | Component, command, query | n/a | n/a |
| Component | `src/features/<x>/components/*.tsx` with `"use client"` | Page | n/a | n/a |

## 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](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#the-confirmation-contract-in-commands).
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

```ts src/features/invoices/services/commands/create-invoice-command.ts theme={null}
"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/shared/lib/prisma";
import { requireModuleAccess } from "@/shared/lib/auth/require-module-access";
import { assertServiceModeConfirmed } from "@/shared/lib/auth/service-mode";
import { handleCommandError } from "@/shared/utils/error-handling";
import type { OperationResult } from "@/shared/types/common";
import { createInvoiceSchema } from "../../contracts/invoice.schemas";

export async function createInvoiceCommand(
  input: unknown,
  confirmation?: unknown,
): Promise<OperationResult<{ id: string }>> {
  try {
    const parsed = createInvoiceSchema.safeParse(input);
    if (!parsed.success) {
      return { success: false, error: parsed.error.issues[0]?.message ?? "Invalid input" };
    }

    const context = await requireModuleAccess("invoices");
    assertServiceModeConfirmed(context, confirmation);

    if (context.orgRole === "member") {
      return { success: false, error: "Not allowed" };
    }

    const invoice = await prisma.invoice.create({
      data: { ...parsed.data, organizationId: context.organizationId },
      select: { id: true },
    });

    revalidatePath("/invoices");
    return { success: true, data: { id: invoice.id } };
  } catch (error) {
    return handleCommandError(error, "Could not create the invoice");
  }
}
```

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.

> [!TIP]
>
> 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`:

```ts src/features/users/services/commands/invite-user-command.ts theme={null}
export async function inviteUserCommand(
  input: unknown,
  confirmation?: unknown,
): Promise<OperationResult<{ userId: string }> & { warning?: "mail-failed" }> {
  try {
    const admin = await getAdminUserOrNull();
    if (!admin) {
      return { success: false, error: "Brak uprawnień" };
    }

    const parsed = inviteUserSchema.safeParse(input);
    if (!parsed.success) {
      return {
        success: false,
        error: parsed.error.issues[0]?.message ?? "Nieprawidłowe dane",
      };
    }
    const { name, email, role } = parsed.data;

    const context = await getOrgContext();
    assertServiceModeConfirmed(context, confirmation);

    // … check for an existing account, then:
    const invitation = await prisma.invitation.create({
      data: {
        organizationId: context.organizationId,
        email,
        role,
        inviterId: admin.id,
        expiresAt: new Date(Date.now() + INVITATION_TTL_MS),
      },
      select: { id: true },
    });

    // … register the account, record the audit event, send the email
    revalidatePath("/users");
    return mailSent
      ? { success: true, data: { userId } }
      : { success: true, data: { userId }, warning: "mail-failed" };
  } catch (error) {
    return handleCommandError(error, "Nie udało się zaprosić użytkownika");
  }
}
```

> [!NOTE]
>
> 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`:

```ts src/shared/types/common.ts theme={null}
export interface OperationResult<T = unknown> {
  success: boolean;
  data?: T;
  error?: string;
}
```

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:

```ts src/shared/utils/error-handling.ts theme={null}
export class DomainError extends Error {
  name = "DomainError";
}

export function handleCommandError(
  error: unknown,
  defaultMessage: string,
): OperationResult<never> {
  if (isNextRedirect(error)) {
    throw error;
  }
  if (error instanceof DomainError) {
    logger.warn(defaultMessage, { err: error });
    return { success: false, error: error.message };
  }
  logger.error(defaultMessage, { err: error });
  return {
    success: false,
    error: defaultMessage,
  };
}
```

| Situation in the command | Component receives | Log |
| - | - | - |
| Invalid input (`return`) | The validation message | — |
| No session | Next.js redirects to `/sign-in` | — |
| `requireModuleAccess`: no active organization or membership | Next.js redirects to `/no-organization` | — |
| `requireModuleAccess`: no access to the module (`notFound()`) | The command's default message | `error` |
| `getOrgContext()`: `NoOrganizationError` | The command's default message | `error` |
| Service mode without valid confirmation | The confirmation error message | `warn` |
| Expected business error (`return` or `throw new DomainError("…")`) | That message | — / `warn` |
| Anything else (database, better-auth) | The command's default message | `error` |

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.

```ts src/features/invoices/services/queries/invoice-queries.ts theme={null}
import "server-only";

import { prisma } from "@/shared/lib/prisma";
import { getOrgContext } from "@/shared/lib/auth/org-context";
import type { InvoiceListItem } from "../../contracts/invoice.types";

export async function getInvoicesQuery(): Promise<InvoiceListItem[]> {
  const { organizationId } = await getOrgContext();

  return prisma.invoice.findMany({
    where: { organizationId },
    orderBy: { createdAt: "desc" },
    select: { id: true, number: true, createdAt: true },
  });
}
```

`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](https://docs.gatojs.com/concepts/organizations.md#the-organizationid-filter).

## 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`).

```ts src/features/users/contracts/user-account.schemas.ts theme={null}
import { z } from "zod";
import { ORG_ROLES } from "@/shared/lib/auth/roles";

export const inviteUserSchema = z.object({
  name: z.string().trim().min(1).max(200),
  email: z.string().trim().toLowerCase().pipe(z.email()),
  role: z.enum([ORG_ROLES.ADMIN, ORG_ROLES.MEMBER]).default(ORG_ROLES.MEMBER),
});

export type InviteUserValues = z.infer<typeof inviteUserSchema>;
```

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:

```tsx src/features/users/components/invite-user-dialog.tsx theme={null}
"use client";
// …
type InviteUserFormValues = z.input<typeof inviteUserSchema>;

export function InviteUserDialog() {
  const router = useRouter();
  const t = useTranslations("users");
  const serviceModeAction = useServiceModeAction();

  const { register, handleSubmit, control, reset, formState } =
    useForm<InviteUserFormValues, unknown, InviteUserValues>({
      resolver: zodResolver(inviteUserSchema),
      defaultValues: { name: "", email: "", role: ORG_ROLES.MEMBER },
    });

  async function onSubmit(values: InviteUserValues) {
    const result = await serviceModeAction.run(inviteUserCommand, values);
    if (result === null) {
      return;
    }
    if (result.success) {
      if (result.warning === "mail-failed") {
        toast.warning(t("toast-invite-mail-failed"));
      } else {
        toast.success(t("toast-invited"));
      }
      handleOpenChange(false);
      router.refresh();
    } else {
      toast.error(result.error ?? t("toast-invite-error"));
    }
  }
  // …
  return (
    <>
      {/* … form … */}
      {serviceModeAction.dialog}
    </>
  );
}
```

* **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

| Rule | Enforced by |
| - | - |
| No comments except `// WHY: …` (up to 3 lines) and tool directives | A Claude Code hook (`.claude/hooks/block-comments.mjs`) for AI edits; code review otherwise |
| `@ts-expect-error` only with a description; no `@ts-ignore` | ESLint (`@typescript-eslint/ban-ts-comment`) |
| No nested ternaries | ESLint (`no-nested-ternary`) |
| Braces on every `if`, `else` and loop | ESLint (`curly`) |
| Error classes set `name` to a string literal | ESLint (`no-restricted-syntax`) |
| No `any`; external data is `unknown` and narrowed by validation | ESLint (`@typescript-eslint/no-explicit-any`), TypeScript `strict` |
| No silent `catch`: log, return an error result, show a message or rethrow | Code review |
| Business logic and Prisma outside components, pages, layouts and route handlers | Code review |
| Every external input validated with Zod from `contracts/` | Partly TypeScript, otherwise code review |
| Session guard and `assertServiceModeConfirmed` before Prisma in actions and queries | Architecture test |
| Actions return `OperationResult` via `handleCommandError` | Code review |
| Formatting | Prettier on commit (lint-staged) |

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:

```ts src/__tests__/server-entrypoints-guard.test.ts theme={null}
const SESSION_GUARDS = new Set([
  "getOrgContext",
  "requireModuleAccess",
  "getAdminUserOrNull",
  "requireUser",
  "getCurrentUser",
  "getImpersonatedByUserId",
  "getSession",
]);
```

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>`.

| Cause | Fix |
| - | - |
| Exported helper without a guard in a query or `"use server"` file | Remove `export`, or move it to a file outside `services/queries/` without `"use server"`. |
| Guard called through your own helper in another file | Call the guard directly, or through a function in the same file. |
| Prisma before the guard | Move the guard to the top of the function. |
| Missing `assertServiceModeConfirmed`, even in a read-only action | Add it right after the context. Move page reads into a query. |
| `assertServiceModeConfirmed` after Prisma | Move it right after `getOrgContext()` / `requireModuleAccess()`. |
| Second argument is a literal, a local variable, a defaulted or reassigned parameter | Pass the `confirmation` parameter unchanged. |
| A `UNGUARDED_ALLOWED` entry no longer matches | Fix or remove the entry. |

### 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:

```ts src/__tests__/server-entrypoints-guard.test.ts theme={null}
const UNGUARDED_ALLOWED = new Map([
  [
    "src/features/organizations/services/queries/default-organization-query.ts#getDefaultActiveOrganizationId",
    "called by the session.create.before hook with the userId of the session being created",
  ],
]);
```

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.

> [!WARNING]
>
> 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](https://docs.gatojs.com/concepts/organizations.md#runtime-guard) are for.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.