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

# Core features

> Reference for the five GatoJS core features (auth, organizations, users, account, dashboard): their pages, components, server actions, queries and the shared code they build on.

Every GatoJS project starts with five features in `src/features/`. Together they cover sign-in, organizations, user management, the account page and an empty dashboard for your own content. This page lists what each one contains, so you know where to look before you change it.

## Overview

| Feature | Pages | Menu entry | Page guard | Translation namespace |
| - | - | - | - | - |
| [`auth`](#auth) | `/sign-in`, `/sign-up`, `/forgot-password`, `/reset-password`, `/set-password` | none | none; pages work without a session | `auth` |
| [`organizations`](#organizations) | `/accept-invitation/<id>`, `/no-organization` | none | none; pages read the session themselves | `organizations` |
| [`users`](#users) | `/users` | **Users** or **Members**, order 80 | `requireModuleAccess("users")` | `users` |
| [`account`](#account) | `/account` | **Account**, order 90 | `requireModuleAccess("account")` | `account` |
| [`dashboard`](#dashboard) | `/dashboard` | **Dashboard**, order 10 | `requireModuleAccess("dashboard")` | `dashboard` |

Pages live in `src/app/[locale]/`, not in the feature folders, because the App Router owns routing. No core feature imports another feature's code. They meet only in a few composition points:

| Place | File | What it takes from features |
| - | - | - |
| `(app)` layout, shared by `/dashboard`, `/users`, `/account` and module pages | `src/app/[locale]/(app)/layout.tsx` | `organizations`: `OrgSwitcher`, `getSwitchableOrganizationsQuery`. `users`: `ImpersonationBanner`, `logImpersonationStopCommand`. Plus the shared sidebar and service-mode components. |
| `/users` | `src/app/[locale]/(app)/users/page.tsx` | `users`: `UsersManager`, `getUserAccountsQuery`. `organizations`: `OrganizationMembers`, `getOrganizationMembersQuery`. |
| `/account` | `src/app/[locale]/(app)/account/page.tsx` | `account`: `AccountDetails`. `auth`: `ChangePasswordForm`. |
| better-auth config | `src/shared/lib/auth/index.ts` | `auth`: `enforceSignupPolicy`. `organizations`: `resolveSignupMembership`, `applySignupMembership`, `getDefaultActiveOrganizationId`. |

The `services/` folders of `auth`, `organizations` and `users` are security code (sign-up, organizations, roles, invitations). They are listed as critical in `mutation-gate.json`, so a surviving mutant there blocks the mutation gate. See [Testing](https://docs.gatojs.com/guides/testing.md).

## Server actions and the service-mode contract

A command on organization data follows a fixed contract: signature `(input: unknown, confirmation?: unknown)`, a call to `assertServiceModeConfirmed(context, confirmation)` right after `getOrgContext()` or `requireModuleAccess()` and before Prisma, and a call from the UI through `useServiceModeAction().run`. This makes a superadmin confirm every change in an organization they do not belong to. See [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

The core has five server actions. One of them falls under the contract:

| Server action | Feature | Contract | Why |
| - | - | - | - |
| `inviteUserCommand` | `users` | yes | Writes an invitation and an account in the active organization. Called through `run`. |
| `enterOrganizationCommand` | `organizations` | no | Changes the session's active organization, not organization data. |
| `changePasswordCommand` | `auth` | no | Changes the user's own password. Signature `(currentPassword, newPassword)`. |
| `logImpersonationStartCommand`, `logImpersonationStopCommand` | `users` | no | Only write a log entry; no Prisma, no organization context. |

> [!TIP]
>
> New commands you write on organization data should follow the contract. The architecture test enforces `assertServiceModeConfirmed` before Prisma in every `"use server"` function that calls `getOrgContext` or `requireModuleAccess`. See [Code patterns](https://docs.gatojs.com/guides/code-patterns.md).

## `auth`

Sign-in, sign-up and passwords: the forms of the `(auth)` pages, the change-password form, the change-password action and the sign-up gate called from a better-auth hook. Flows are described in [Auth and roles](https://docs.gatojs.com/concepts/auth-and-roles.md).

**Module definition:** `key: "auth"`, `nav: []`, `public: true`. No page calls `requireModuleAccess("auth")`, so the definition has no runtime effect. The `(auth)` pages work without a session because they call no guard, not because of `public`.

### Pages

| Path | Contents |
| - | - |
| `/sign-in` | `SignInForm`. |
| `/sign-up` | With `AUTH_PUBLIC_SIGNUP=false` and no `invitationId`: redirect to `/sign-in`. Otherwise `SignUpForm`. |
| `/forgot-password` | `ForgotPasswordForm`. |
| `/reset-password` | `ResetPasswordForm`. |
| `/set-password` | `SetPasswordForm`. The welcome email after **Invite user** links here. |

The `(auth)` layout only centers the content. These pages do not check the session, so a signed-in user also sees the forms.

### Components

All are client components in `src/features/auth/components/` that call better-auth through `authClient`.

| Component | What it does |
| - | - |
| `SignInForm` | Validates with `signInSchema`, calls `authClient.signIn.email`, then always goes to `/dashboard`. |
| `SignUpForm({ invitationId })` | Validates with `signUpSchema`, calls `authClient.signUp.email` (with `invitationId` when present), then goes to `/sign-in`. |
| `ForgotPasswordForm` | Calls `authClient.requestPasswordReset` with `redirectTo: "/reset-password"`. |
| `PasswordTokenForm` | Shared new-password form: reads `token` from the URL and calls `authClient.resetPassword`; shows an expired-link card without a token. |
| `ResetPasswordForm`, `SetPasswordForm` | `PasswordTokenForm` with reset or welcome texts. |
| `ChangePasswordForm` | Card on `/account`; calls `changePasswordCommand` directly. |

### Contracts and services

Zod schemas in `contracts/auth.schemas.ts` (`signInSchema`, `signUpSchema`, `forgotPasswordSchema`, `resetPasswordSchema`, `changePasswordSchema`) validate forms in the browser. On the server, better-auth validates the data, including the minimum password length of 8.

| Function | Kind | What it does |
| - | - | - |
| `changePasswordCommand(currentPassword, newPassword)` | server action | Changes the signed-in user's password via `auth.api.changePassword`, keeping other sessions. |
| `enforceSignupPolicy(body, publicSignup)` | service, better-auth `before` hook on `/sign-up/email` | With public sign-up off, throws 403 unless a pending, valid invitation matches the `invitationId` and email in the request. |
| `assertSignupAllowed({ publicSignup, hasInvitation })` | service | Throws `FORBIDDEN` when sign-up is disabled and there is no matching invitation. |

## `organizations`

The organization switcher, the invitation page, the no-organization page, the members view for organization roles, and the membership created at sign-up. The data model and active organization are covered in [Organizations](https://docs.gatojs.com/concepts/organizations.md).

**Module definition:** `key: "organizations"`, `nav: []`, `public: true`. Like `auth`, no page reads it.

### Pages

| Path | Contents |
| - | - |
| `/accept-invitation/<id>` | Without a session: **Sign in** and **Create account** (`/sign-up?invitationId=<id>`). With a session: accepts the invitation, sets the organization active and redirects to `/dashboard`, or shows "Could not accept the invitation". |
| `/no-organization` | **No organization** card with a list of organizations to enter (when there are any), `CreateOrganizationForm` (only with `MULTI_ORG=true`) and a sign-out button. Redirects to `/dashboard` when a working organization context exists. |

Both pages sit outside `(app)`, so they do not require an active organization and have no sidebar.

> [!NOTE]
>
> `/accept-invitation/<id>` is the only core page that changes data in `page.tsx`, on page load. New code should do this in a server action instead. See [Code patterns](https://docs.gatojs.com/guides/code-patterns.md).

### Components

| Component | What it does |
| - | - |
| `OrgSwitcher({ organizations, activeOrganizationId, canCreateOrganization })` | Shows a select when there is more than one organization (calls `enterOrganizationCommand`, then `router.refresh()`), and a **+** button that opens **Create organization** when `MULTI_ORG=true`. |
| `CreateOrganizationForm({ onCreated })` | Calls `authClient.organization.create` with a slug from `slugifyOrganizationName`, then goes to `/dashboard` in the new organization. |
| `EnterOrganizationList({ organizations })` | **Enter an organization** list on `/no-organization`. |
| `OrganizationMembers(...)` | The **Members** view on `/users`. Organization owners and admins change roles, remove members (except the owner and themselves), invite people and cancel pending invitations. |
| `SignOutButton` | Signs out and goes to `/sign-in`. |

`CreateOrganizationForm` and `OrganizationMembers` change data through better-auth endpoints (`authClient.organization.*`), not kit commands, so they show no service-mode dialog.

### Commands, queries and services

| Function | Kind | What it does |
| - | - | - |
| `enterOrganizationCommand(organizationId)` | server action | Sets the session's active organization when `canEnterOrganization` allows it. A superadmin entering without membership records an `organization.entered` audit event. |
| `joinOrganizationCommand(...)`, `createOrganizationWithOwnerCommand(...)` | internal (no `"use server"`) | Create a membership (accepting the invitation in the same transaction), or an organization with an owner. Called only during sign-up. |
| `resolveSignupMembership(...)` | service, `before` hook on `/sign-up/email` | Decides where a new account goes: join the invitation's organization or the oldest one, or create a new organization. |
| `applySignupMembership(userId, membership)` | service, `user.create.after` hook | Carries out that decision. |
| `canEnterOrganization(...)` | service | `true` if the organization exists (superadmin) or the user is a member. |
| `getOrganizationMembersQuery()` | query, guard `getOrgContext()` | Members and pending invitations of the active organization. |
| `getSwitchableOrganizationsQuery()` | query, session guard | Organizations for the switcher: all of them for a superadmin, memberships for everyone else. |
| `getDefaultActiveOrganizationId(userId)` | query, `session.create.before` hook | The active organization for a new session: the oldest membership, or for a superadmin without memberships, the oldest organization. |

## `users`

Accounts seen through the global role: the list of all accounts, **Invite user** and impersonation. The same `/users` page shows the **Members** view from `organizations` to accounts with the global role `user`.

```ts src/features/users/module.ts theme={null}
export default defineModule({
  key: "users",
  nav: [{ href: "/users", labelKey: "nav", multiOrgLabelKey: "nav-members", icon: "users", order: 80 }],
  routePrefixes: ["/users"],
  adminOnly: true,
  multiOrgRoles: ["owner", "admin"],
});
```

Global `admin` and `superadmin` always have access. Organization roles get access only with `MULTI_ORG=true`, and only `owner` and `admin`; for them the menu label switches to **Members**. A `member` never gets this page.

### Page

`/users` calls `requireModuleAccess("users")`, then picks a view by global role:

* `admin` or `superadmin`: `getUserAccountsQuery()` and `UsersManager`.
* Everyone else (organization owners and admins in multi-org mode): `getOrganizationMembersQuery()` and `OrganizationMembers`.

### Components

| Component | What it does |
| - | - |
| `UsersManager({ users, currentUserId, currentUserRole, adminImpersonation })` | **Users** card with the account table and **Invite user**. **Sign in as** calls `authClient.admin.impersonateUser`, logs the start and goes to `/dashboard`. |
| `buildUserAccountColumns(...)` | Builds the table columns: name, email, role badge, created date and the **Sign in as** button where allowed. |
| `InviteUserDialog` | Name, email and organization role (`member` or `admin`). Submits through `useServiceModeAction().run(inviteUserCommand, values)`; the only core component that uses `run`. |
| `ImpersonationBanner({ active, userName, onStopLogged })` | "Signed in as …" bar in the `(app)` layout with a button to return to your own account. |

> [!NOTE]
>
> The role badge for `superadmin` reads "Service (Web Amigos)" in the kit's translations. Rename it in `src/features/users/i18n/*.json` (`role-superadmin`) to the name of your own team.

### Actions and queries

| Function | Kind | What it does |
| - | - | - |
| `inviteUserCommand(input, confirmation?)` | server action, follows the contract | Creates an account with an invitation in the active organization, records `member.invited`, and emails a set-password link. Returns `warning: "mail-failed"` if the email could not be sent. |
| `logImpersonationStartCommand()`, `logImpersonationStopCommand()` | server action | Inside an impersonated session, write `[USERS] Impersonation started` / `stopped` to the log. |
| `getUserAccountsQuery()` | query, admin guard | All accounts, newest first. Redirects to `/sign-in` without a session; 404 without a global admin role. |

`getUserAccountsQuery` does not filter by `organizationId`: an account belongs to the whole app, not to an organization, and only global admins see this list.

> [!WARNING]
>
> The impersonation log entry is written only when the UI calls the log action. Impersonating through the better-auth endpoint directly, bypassing the UI, leaves no entry.

## `account`

The signed-in user's account page. `AccountDetails({ name, email })` is a server component showing the name and email; the change-password form comes from `auth`. There is no form to change the name or email.

**Module definition:** `key: "account"`, one nav item (`/account`, icon `user-cog`, order 90). No role restrictions, so every account with an active organization can open it. The sidebar's user menu also links to `/account`.

## `dashboard`

The start page after sign-in. `DashboardPlaceholder({ userName })` shows a heading, "Welcome, `<name>`" and "Your application content will appear here." Replace it with your own content.

**Module definition:** `key: "dashboard"`, one nav item (`/dashboard`, icon `layout-dashboard`, order 10). No role restrictions.

> [!WARNING]
>
> `/dashboard` is hard-coded as the destination in six places. If you change the start page, update all of them: `SignInForm`, the accept-invitation page (`APP_HOME_PATH`), the no-organization page, `EnterOrganizationList`, `CreateOrganizationForm` and `UsersManager`.

## Shared parts

Code in `src/shared/` and `src/components/ui/` belongs to the core module but is not a feature: every feature uses it.

### Sidebar

`src/shared/components/app-sidebar.tsx` (client component) exports `SidebarProvider`, `useSidebar()`, `MobileHeader` and `AppSidebar({ accessContext, userName, userEmail })`. Menu entries come from module definitions, not from this file: you add one with a `nav` item in `module.ts`. The layout passes the roles from the organization context and `MULTI_ORG`, so the menu shows exactly what `requireModuleAccess` allows.

### Service mode UI

`src/shared/components/service-mode/`:

| Export | What it does |
| - | - |
| `ServiceModeProvider`, `useServiceMode()` | Service-mode state for components, set by the `(app)` layout. |
| `ServiceModeBanner` | The "Service mode: `<organization>`" bar. |
| `useServiceModeAction()` | Returns `{ run, requestConfirmation, dialog }`. `run(command, input)` calls the command directly outside service mode, and after confirmation inside it; returns `null` on cancel. `requestConfirmation()` asks the same question for writes that are not server actions. |

### Project name

```ts src/shared/config/project.ts theme={null}
export const project = {
  name: "Acme CRM",
  slug: "acme-crm",
} as const;
```

`create` fills this in. `name` is used for the page title, the sidebar header, email templates and the default first organization name in `admin:create`. `slug` names the logger and the default OpenTelemetry `service.name`. The email sender is separate, in `EMAIL_FROM`.

### Types and utilities

| File | Export | Purpose |
| - | - | - |
| `src/shared/types/common.ts` | `OperationResult<T>` | `{ success, data?, error? }`, returned by server actions. |
| `src/shared/utils/error-handling.ts` | `DomainError`, `handleCommandError(error, defaultMessage)` | Shared error handling for actions: rethrows Next.js redirects, turns a `DomainError` into its message, and any other error into `defaultMessage`, so technical details never reach the browser. |
| `src/shared/lib/utils.ts` | `cn(...)` | Merges Tailwind classes (`clsx` + `tailwind-merge`). |
| `src/shared/constants/table-pagination.ts` | `TABLE_PAGE_SIZE_OPTIONS` | Default page sizes for `DataTablePagination`. |

### UI components

`src/components/ui/` holds shadcn/ui-style components built on `@base-ui/react` primitives (style `base-nova` in `components.json`), plus `DataTable` on TanStack Table, `Toaster` on sonner and a `cmdk` command menu.

Two behaviors that are easy to assume otherwise:

* **`form.tsx` is not bound to react-hook-form.** It provides layout pieces (`FormField`, `FormLabel`, `FormError`, `FormHint`). Forms wire fields to `useForm` themselves with `register` or `Controller`.
* **`DataTable` does not paginate on its own.** Without `pagination` it shows all rows and sorts them client-side. With `pagination`, sorting and paging belong to the caller (`manualSorting`, `manualPagination`). Column visibility is remembered in `localStorage` only if you pass `storageKey`.


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