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

# Architecture

> How GatoJS is put together: the kit, the core and modules, code copied into your repository instead of installed, the request path from browser to Prisma, and defineModule.

GatoJS is a working Next.js 16 application that a CLI copies into your repository. After that it is your code. This page explains how the pieces are organized, what happens on each request, and which layer is responsible for which check.

## Kit, core and modules

> [card] Kit
>
> The GatoJS repository: one reference application plus a manifest per module saying which files and npm dependencies belong to it.

> [card] Core
>
> What every project gets: sign-in, organizations, users, account and dashboard, plus shared libraries and tooling.

> [card] Modules
>
> Optional units you add and remove with the CLI: `audit-logs`, `api-keys`, `uploads`.

A few terms come up throughout the docs:

| Term | Meaning |
| - | - |
| **Feature** | A folder `src/features/<x>/` with the code for one piece of functionality. The core has five: `auth`, `organizations`, `users`, `account`, `dashboard`. |
| **Kit module** | What the CLI copies into a project and removes from it. It is described by a manifest: its files, npm dependencies, and what it contributes to core files (env variables, schema relations, Docker services, CI steps). A module can contain several features; the core itself is the module `core`. |
| **Project module** | A feature you wrote in your project, registered with a manifest under `projectModules` in `.wa/kit.json`. The generator treats it like a kit module; the CLI never copies or deletes it. |
| **Module definition** | `src/features/<x>/module.ts`, created with `defineModule(...)`. Despite the name, it describes one feature: its key, menu entries and access rules. |
| **Module registry** | The generated files `src/modules.generated.ts` and `src/modules.client.generated.ts`, from which the app learns which features exist. |
| **Seam** | A place where the core learns about modules: a generated file, or a `wa:<name>` region inside a core file. See [Module registry](https://docs.gatojs.com/concepts/module-registry.md). |
| **Guard** | A function that checks the session or permissions before code touches data, for example `getOrgContext()` or `requireModuleAccess()`. |
| **Organization context** | The result of `getOrgContext()`: `{ userId, organizationId, orgRole, userRole, serviceMode }` for the signed-in user and their active organization. See [Organizations](https://docs.gatojs.com/concepts/organizations.md). |

## Copied into your repo, not installed

The core and modules are copied into your repository, not installed from npm. You change them like any other file, with no fork and no package to publish. The trade-off is deliberate:

| | A framework package | GatoJS |
| - | - | - |
| Changing behavior | Config options, overrides or a fork | Edit the file |
| Reading the source | Somewhere in `node_modules` | In your editor, next to your code |
| What breaks your app | An upgrade you did not write | A change you made and can see in git |
| Getting upstream fixes | `npm update` | Pulled in deliberately with [`gato update`](https://docs.gatojs.com/cli/update), which merges your local changes |

The CLI ([`gato`](https://docs.gatojs.com/cli/overview)) creates projects, adds and removes modules, lists them, updates the kit version and regenerates the registry. It does not push your changes back to the kit: a fix that would help other projects goes to the [GatoJS repository](https://github.com/webamigos/gatojs) as a pull request.

## Kit principles

These decisions shape the rest of the codebase.

* **Kit code becomes project code.** See above.
* **The kit is one reference application.** It lives at the root of the GatoJS repository with the same layout as a generated project, so it is developed and tested like a normal app. Each file belongs to exactly one module, and a test enforces that.
* **A module only adds files.** It never edits core files. The core learns about a module only through seams: the generated registry and `wa:*` regions. In the other direction, a module uses the core through entry points such as `trackAudit` and declarations in `defineModule`. If modules edited core files, every add, remove or update would turn into merging someone else's changes into the same files.
* **Generated files are committed.** The project builds, tests and deploys without the CLI (the Docker image never runs it). CI checks that the committed files match the generator's output exactly.
* **A module definition is pure data.** The server-side page guard and the browser-side menu both read it, and both decide access with the same function, `canAccessModule`. The menu therefore shows exactly the pages the guard lets you open.
* **Modules bring their own schema; features bring their own translations.** Prisma models go in a module's own file in `prisma/schema/`; translations go in `src/features/<x>/i18n/` under a namespace equal to the folder name. Back-relations on core models go into the `wa:relations` region.
* **The server checks data and access, not the UI.** Every query on domain data filters by `organizationId` from `getOrgContext()`. Every feature page in `(app)` calls `requireModuleAccess(key)`. Every server action checks permissions itself. Hiding a menu entry protects nothing, because a URL can be typed by hand.
* **Logs and traces go through OpenTelemetry.** The logger sends entries through the OpenTelemetry logs API, and `OTEL_EXPORTER_OTLP_ENDPOINT` turns on export. See [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md).

## Runtime services

The app is a single Node.js process. better-auth (sessions), Prisma (database access) and next-intl (translations) are libraries inside that process, not separate services.

```mermaid theme={null}
flowchart LR
    browser["Browser"]
    app["Next.js app"]
    db[("PostgreSQL")]
    mail["mailpit (local) / Resend (production)"]
    otlp["OTLP collector (optional)"]

    browser -->|"HTTP(S)"| app
    app -->|"DATABASE_URL"| db
    app -->|"SMTP_URL or RESEND_API_KEY"| mail
    app -.->|"OTEL_EXPORTER_OTLP_ENDPOINT"| otlp
```

* **Browser → app.** Pages, server actions (POST requests to the current page URL), the better-auth endpoint `/api/auth/*`, and `/api/healthcheck`, which runs `SELECT 1` for the deployment health check.
* **App → PostgreSQL.** Prisma with the `@prisma/adapter-pg` driver adapter. better-auth stores accounts and sessions in the same database.
* **App → email.** SMTP when `SMTP_URL` is set (mailpit locally), otherwise Resend when `RESEND_API_KEY` is set, otherwise a log entry only. Production requires `RESEND_API_KEY`. See [Email](https://docs.gatojs.com/guides/email.md).
* **Module services.** `uploads` stores files on local disk or S3-compatible storage. `uploads` and `api-keys` add their own API routes.

Locally, `npm run dev` runs the app and `docker compose up -d` runs PostgreSQL and mailpit. In production the app runs from the `Dockerfile` image; see [Docker](https://docs.gatojs.com/deployment/docker.md) and [Railway](https://docs.gatojs.com/deployment/railway.md).

## The request path

Two flows show where each check happens: rendering a page (GET) and running a server action (POST). Both pass through the proxy first.

### Proxy: locale only

`src/proxy.ts` is the Next.js 16 proxy (formerly middleware). In GatoJS it only resolves the locale with next-intl; it does **not** check sessions or permissions.

```ts src/proxy.ts theme={null}
import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";

export default createMiddleware(routing);

export const config = {
  matcher: ["/((?!api(?:/|$)|_next|_vercel|.*\\..*).*)"],
};
```

The matcher skips `/api` and everything below it, Next.js internals, and any path with a dot. A path that merely starts with `api`, like `/api-keys`, still goes through the proxy. A URL without a locale prefix is rewritten to the default locale (`pl`), unless next-intl detects English from the `NEXT_LOCALE` cookie or `Accept-Language`, in which case it redirects to `/en/...`.

> [!WARNING]
>
> Because of the matcher, a feature page cannot live at `/api`, under `/api/`, or contain a dot in its path. Without a locale prefix it would return 404.

### Rendering a page

An organization owner opens `/users` with `MULTI_ORG=true`:

```mermaid theme={null}
sequenceDiagram
    participant B as Browser
    participant P as proxy
    participant L as (app) layout
    participant S as users page
    participant R as requireModuleAccess
    participant G as getOrgContext
    participant Q as query
    participant D as PostgreSQL

    B->>P: GET /users
    P->>L: rewrite to /pl/users
    par layout
        L->>G: getOrgContext()
        G->>D: session + membership
        L-->>B: sidebar, org switcher, banners
    and page
        S->>R: requireModuleAccess("users")
        R->>G: getOrgContext()
        R->>R: canAccessModule(definition, roles, MULTI_ORG)
        R-->>S: OrgContext
        S->>Q: getOrganizationMembersQuery()
        Q->>G: getOrgContext()
        Q->>D: where organizationId = context.organizationId
        Q-->>S: members and invitations
    end
    S-->>B: HTML with security headers
```

The layout and the page render independently, and the layout does not re-render on client-side navigation between pages. That is why the layout check is not enough: the page calls its own guard, and the query calls `getOrgContext()` again before touching Prisma. `getOrgContext()` reads the session from the database rather than the cookie cache, so role and membership changes take effect immediately.

### Running a server action

A global admin submits **Invite user**:

```mermaid theme={null}
sequenceDiagram
    participant F as InviteUserDialog
    participant H as useServiceModeAction().run
    participant C as inviteUserCommand
    participant G as getOrgContext
    participant A as assertServiceModeConfirmed
    participant D as PostgreSQL

    F->>H: run(inviteUserCommand, values)
    H->>C: POST /users (Next-Action header)
    C->>C: check role, validate input with Zod
    C->>G: getOrgContext()
    G-->>C: OrgContext
    C->>A: assertServiceModeConfirmed(context, confirmation)
    C->>D: create invitation with context.organizationId
    C-->>F: OperationResult
```

A server action is an exported function from a `"use server"` file. Next.js calls it directly: the layout and page do **not** run first, so their checks do not protect it. The command therefore checks the role, validates input, gets the organization context and confirms service mode before it reaches Prisma. Every command on organization data follows this contract; see [Code patterns](https://docs.gatojs.com/guides/code-patterns.md) and [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

### Who checks what

| Layer | Checks | When the check fails |
| - | - | - |
| Proxy (`src/proxy.ts`) | Locale only. | Never blocks; at most redirects to a locale. |
| `[locale]` layout | That the segment is one of the project's locales. | 404. |
| `(app)` layout | Session and active organization via `getOrgContext()`. | No session: redirect to `/sign-in`. No active organization or membership: redirect to `/no-organization`. |
| Feature page in `(app)` | `requireModuleAccess(key)`: session, active organization and access to the module definition. | As above; no access or unknown key: 404. |
| Command on organization data | Its own guard, input validation, `assertServiceModeConfirmed` before Prisma. | `OperationResult` with `success: false`, or a redirect from the guard. |
| Query (`services/queries/`) | Its own session guard before Prisma. | Redirect, 404 or an error, depending on the guard. |
| Database query | An explicit `organizationId` filter from the context in every query. The tenant-scope Prisma extension throws `TenantScopeError` on a query against a model with `organizationId` (other than `Member` and `Invitation`) that has no organization filter. | Error. Deliberate cross-organization reads go through `withoutTenantScope(reason, fn)`. |
| better-auth endpoint | better-auth rules and the hooks in `src/shared/lib/auth/index.ts`. | Error returned by better-auth. |
| Anywhere | Unexpected errors, such as an unreachable database. | In pages: an error page. In actions: `handleCommandError` logs the error and returns a generic message, so technical details never reach the browser. |

An architecture test (`src/__tests__/server-entrypoints-guard.test.ts`) checks that every exported function in a `"use server"` file and in `services/queries/` calls a guard before Prisma. That a new page calls `requireModuleAccess` is a convention, not a test.

> [!NOTE]
>
> A superadmin without membership in the active organization does not get redirected. They get a context with `serviceMode: true`, and the layout shows the service-mode banner. See [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

## Module definition

A feature needs a `module.ts` to have a menu entry or a page protected by `requireModuleAccess`. Each core feature has one:

```ts src/features/users/module.ts theme={null}
import { defineModule } from "@/shared/lib/modules/define-module";

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

`defineModule` returns its argument unchanged; it exists so TypeScript checks the object against `ModuleDef` and keeps its exact type. Two places in the core read definitions, both from `clientModules` in the client registry:

* **The page guard.** `requireModuleAccess(key)` finds the definition with that key (404 if none), then calls `canAccessModule(definition, { userRole, orgRole, multiOrg })`.
* **The sidebar.** `getNavEntries` keeps the definitions `canAccessModule` allows, collects their `nav` items and sorts them by `order` across all features. The label is the translation at `<key>.<labelKey>`.

`canAccessModule` decides in this order:

1. Global `admin` and `superadmin`, or a definition with `public: true`: allowed.
2. No organization role: denied.
3. `adminOnly: true`: allowed only when `MULTI_ORG=true` and the organization role is in `multiOrgRoles`.
4. Otherwise: allowed if `roles` is not set or contains the organization role.

> [!WARNING]
>
> `module.ts` must not import server code. The sidebar is a client component, so everything `module.ts` imports ends up in the browser bundle.

### `ModuleDef` reference

**key** `string` *required*

Identifier passed to `requireModuleAccess(key)` and the start of the menu label path. Must equal the feature folder name.

**nav** `ModuleNavItem[]` *required*

Sidebar entries. Can be `[]`.

**routePrefixes** `string[]` *required*

The feature's routes. Required by the type, but it does **not** protect any route; only `requireModuleAccess` in the page does.

**roles** `OrgRole[]`

Limits access to these organization roles (`owner`, `admin`, `member`). Without it, every role has access. Ignored when `adminOnly` is `true`.

**public** `boolean`

`true` grants access to every role. It does **not** mean "no sign-in": a page with `requireModuleAccess` still needs a session and an active organization.

**adminOnly** `boolean`

`true` grants organization roles access only with `MULTI_ORG=true`, and only to roles in `multiOrgRoles`.

**multiOrgRoles** `OrgRole[]`

Used only together with `adminOnly: true`. Defaults to an empty list.

**auditActions** `\{ action, labelKey \}[]`

Audit actions with label keys, read by the [`audit-logs`](https://docs.gatojs.com/modules/audit-logs) module. Pure data: without the module nothing reads it.

**apiScopes** `\{ key, labelKey \}[]`

Scopes the feature exposes to API keys, read by the [`api-keys`](https://docs.gatojs.com/modules/api-keys) module.

**uploadPurposes** `\{ key, mimeTypes, maxBytes, visibility, resizeImage? \}[]`

Upload purposes with allowed MIME types, a size limit, visibility (`public` or `organization`) and optional image resizing, read by the [`uploads`](https://docs.gatojs.com/modules/uploads) module.

`ModuleNavItem` has `href` (path without the locale prefix), `labelKey`, optional `multiOrgLabelKey` (used instead of `labelKey` when `MULTI_ORG=true` and the user has the global role `user`), `icon` (a lucide icon name such as `layout-dashboard`) and `order`. Core entries use `dashboard` 10, `users` 80 and `account` 90.


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