Skip to main content
This tutorial adds a small domain feature to a GatoJS project: organization notes. By the end of part 2 you will have a notes feature with a notes table, a /notes page with a list and a form, a listNotesQuery query, a createNoteCommand command and tests that prove one organization cannot see or write another organization’s notes. Part 1 (this page) covers steps 1–6: registering the feature, the database schema, contracts and the tests that are red before the implementation exists. Part 2 covers the query, command, component, page, the quality gates and the commit.
This tutorial builds a project feature: code that lives in one application. If you want to write a module that ships to many projects through the kit, see New kit module.

What you will build

A few terms used throughout:
  • Feature: a folder src/features/<name>/ holding the code of one feature.
  • Module: an entry in .wa/kit.json with a manifest that lists the feature’s files. Kit modules live under modules; your own features live under projectModules.
  • Module definition: the feature’s module.ts, created with defineModule(...).
  • Module registry: the generated files src/modules.generated.ts and src/modules.client.generated.ts. The menu, the page guard and the translation loader learn about features only through them. See Module registry.

Step 1. Start from a working project

Your project should already be set up as in the Quickstart: dependencies installed, .env in place, the database running in Docker, the init migration applied and the first account created. Before you continue, check three things, because each one breaks a later step:
  1. Database port. If you changed DB_PORT in .env, the port in DATABASE_URL must match.
  2. Migrations are committed. git ls-files prisma/migrations should list migration_lock.toml and the init migration. An empty result means migrations are ignored; see Database and migrations.
  3. A clean branch. Start on a feature branch, for example git switch -c feat/notes.

Step 2. Feature folder, module definition and translations

The feature lives in src/features/notes/. The folder name is also the translation namespace, and the menu looks up its label under the module key, so key must equal the folder name. Nothing checks this: with key: "note" in a notes folder, the menu shows the raw translation key instead of a label.
src/features/notes/module.ts
  • nav adds one menu item. icon is a lucide icon name, and order: 50 places it between Dashboard (10) and Users (80).
  • routePrefixes is required by the type but does not protect the route. The page is protected by requireModuleAccess("notes"), which you add in part 2.
  • Without roles, adminOnly or public, every role in the organization can access the feature. The optional auditActions, apiScopes and uploadPurposes only matter in projects with the audit logs, API keys or uploads modules.
  • module.ts ends up in the browser bundle through the menu, so it must not import server code.
Add the feature’s strings. Keys are lowercase with hyphens:
src/features/notes/i18n/en.json
Create a translation file for every locale listed in locales in .wa/kit.json (by default pl and en), with the same set of keys. The architecture test i18n-keys-exist-in-every-locale fails npm run verify if a key is missing in one of them. See Internationalization. Now run the generator, as you do after adding a module definition or a translation file:
The output is Bez zmian (“no changes”), and the registry files do not mention notes. That is expected: the generator only registers features matched by a file pattern in a manifest in .wa/kit.json. You add that entry in step 3.
The kit’s CLI and many of its server-side messages are currently in Polish. Bez zmian means “no changes” and zmieniono <file> means “changed <file>”.

What a missing projectModules entry looks like

If a feature has files but no entry, this is what you see: The page guard explains the 404: a key outside the registry is rejected before roles are even considered.
src/shared/lib/auth/require-module-access.ts

Step 3. Add the entry to projectModules

.wa/kit.json has two module sections. modules describes code your project received from the kit, with versions and file hashes used by updates. projectModules describes features written in your project: an entry has only a manifest, with no version tracking or hashes, and gato generate reads it exactly like a kit module. Project modules are registered after kit modules, in alphabetical order. The full format is in the .wa/kit.json reference. Add a notes entry:
.wa/kit.json
When reading the file, the generator enforces four rules on top of the schema, and stops with an error if one fails:
  • the entry key equals manifest.name;
  • the name is not in both modules and projectModules;
  • every module in requires exists in modules or projectModules;
  • files contains a pattern starting with src/features/<name>/.
A typo in a field name, such as schemaRelation, raises no error. The field falls back to its default and the relation never appears.
Run the generator again:
The registry now imports the notes module definition and its translations after the kit modules, and the Organization model contains the relation:
src/modules.client.generated.ts
prisma/schema/organizations.prisma

Prisma errors between steps 3 and 4

The back-relation is added only through schemaRelations and the generator. Three errors can show up along the way:
  • Entry before the schema file (the order in this tutorial). The region references a Note model that does not exist yet, so any Prisma command that loads the schema fails with Type "Note" is neither a built-in type, nor refers to another model, composite type, or enum. Don’t run Prisma until you’ve saved the schema file from step 4.
  • Schema file before the entry. Prisma reports the missing back-relation and suggests Either run `prisma format` or add it manually. Do neither: add schemaRelations and run the generator.
  • After prisma format or a manual edit. prisma format writes notes Note[] below // wa:relations:end, outside the region. The next generator run adds the same line inside the region and the schema fails with Field "notes" is already defined on model "Organization". Delete the line outside the region.
Core tests don’t change when you add a feature. They compare the registry only against the five core modules, while registry-consistency.test.ts checks the whole registry, including notes. Part 2 covers this in verify and the core tests.

Step 4. Schema and migration

Put the Note model in its own schema file. Features never edit core schema files.
prisma/schema/notes.prisma
  • Required organizationId with an index and a relation to Organization. Core domain tables look the same. Every query filters by this column, so it needs an index, and a required column means a note cannot be saved without an organization. Because the model has organizationId, the kit’s runtime tenant-scope guard covers it automatically: a findMany without an organization filter throws TenantScopeError. See Organizations.
  • onDelete: Cascade. Deleting an organization deletes its notes. The foreign key to organizations also means resetDatabase() in integration tests clears the notes table, because TRUNCATE … CASCADE follows foreign keys.
  • @map and @@map. Columns and tables use snake_case, like the core.
Create the migration and regenerate the Prisma client:
migrate dev prints a Datasource "db": … line (check the database name and port there), then:
Your timestamp will differ. The generated SQL:
prisma/migrations/20261028044413_add_notes/migration.sql
In Prisma 7, migrate dev does not generate the client. Without npm run db:generate, TypeScript does not know the model: npx tsc --noEmit fails with error TS2339: Property 'note' does not exist on type 'PrismaClient'.
Commit the migration folder together with the feature: production only applies migrations that are in the repository.

Step 5. Contracts

Contracts are the input schema and the result type. They come before tests because tests and code both depend on them, and because the browser form and the server command validate against the same schema.
src/features/notes/contracts/note.schemas.ts
src/features/notes/contracts/note.types.ts
trim() turns a whitespace-only title into an empty string, which then fails min(1). z.object strips unknown keys, so an organizationId sent from the browser never reaches parsed.data. Still, what protects writes to another organization is not the schema but taking organizationId from the server-side context in the command (part 2). Validation messages are Zod’s defaults, for example Too small: expected string to have >=1 characters. The form shows its own translated message; the server message is only visible to requests that bypass the form.

Step 6. Tests before code

GatoJS expects tests for a task to be written before the implementation, ideally by a different author than the code. A test written after the code by the same author tends to restate the code’s assumptions and pass. With AI agents, the kit ships a dedicated test-writer agent for this; see Built for AI agents. Working alone, keep at least the order: plan, tests, then code.

Plan behaviors and the mutations to kill

Start from a list of behaviors (input → literal expected result) and the code mutations each test must catch: The isolation test has its own behaviors: organization A’s list contains none of B’s notes, a command with A’s context writes to A, passing B’s organizationId in the input does not move the note, and user A with B as the active organization is redirected and writes nothing.

Red for the right reason

Before the implementation, tests must fail because an export is missing or a value is wrong, not because of an import error. If the command file doesn’t exist, Vitest only reports:
So create empty stubs first. The command file contains "use server"; and export {};; the query file contains import "server-only"; and export {};. Now every test fails for the right reason, for example TypeError: createNoteCommand is not a function.
When AI agents do the implementation, write implement to .superpowers/phase in the implementer’s working copy before it starts. The protect-tests hook then blocks edits to test files. See Built for AI agents.

Command unit test

Mock only inputs and outputs: Prisma, the session context (getOrgContext), configuration (env), the logger, the locale, and Next.js notFound, redirect and revalidatePath. Keep requireModuleAccess, the module registry, assertServiceModeConfirmed and handleCommandError real: those are the rules under test.
src/features/notes/services/commands/__tests__/create-note-command.test.ts
  • Mock env. requireModuleAccess reads env.MULTI_ORG, and the first read of env validates every core variable. The CI verify job has no .env, so the real env would fail there even though the test passes locally.
  • Errors carry a digest. handleCommandError recognizes a redirect by a digest starting with NEXT_REDIRECT, just like Next.js. A mock without digest would turn the redirect into a default error message, and the test would check behavior the app doesn’t have.
Two tests from the file. Expected values are literals:
src/features/notes/services/commands/__tests__/create-note-command.test.ts
createdData() returns the data of the first prisma.note.create call, and expectNoWrite() asserts there was no write and no revalidatePath. SERVICE_CONTEXT is a superadmin context with serviceMode: true, and SERVICE_MODE_ERROR is the literal { success: false, error: "Potwierdź zmianę w trybie serwisowym" }, the message thrown by the kit’s assertServiceModeConfirmed. Service mode is explained in Superadmin and service mode.

Isolation test on a real database

A unit test with a mocked Prisma cannot notice a missing organizationId filter, because the mock returns whatever the test prepared. Only a test against real Postgres with two organizations can. Copy the session stubs, the vi.mock calls and signInAs from src/features/organizations/services/__tests__/organization-isolation.integration.test.ts (the Testing guide walks through them), with two changes:
src/features/notes/services/__tests__/notes-isolation.integration.test.ts
  1. redirect with a digest. The core test’s stub throws a plain new Error("NEXT_REDIRECT"). That is enough there, but a command that calls requireModuleAccess inside handleCommandError would turn it into a default error.
  2. Mock next/cache. Outside a Next.js request, revalidatePath throws Invariant: static generation store missing in revalidatePath /notes. The command catches it after the write, so the row is saved but the result is a failure. Assert the command result as well as the database contents, or this goes unnoticed.
Seed both organizations from literals in beforeEach:
src/features/notes/services/__tests__/notes-isolation.integration.test.ts
The write test compares both organizations with literals. titlesIn(org) reads an organization’s note titles directly through prisma, sorted alphabetically:
src/features/notes/services/__tests__/notes-isolation.integration.test.ts

Run the tests

npx vitest run skips *.integration.test.ts, so the isolation test needs npm run test:integration. Without INTEGRATION_DATABASE_URL, it connects to postgresql://postgres:postgres@localhost:5432/wa_app_test. If your database runs on another port, set the variable in the shell (an entry in .env is not read):
Integration tests wipe their database. The only safeguard is that the database name must end in _test; the host and port are not checked. Read Commands that reset a database before the first run.
Before the implementation, both runs are red with TypeError: … is not a function. That is the state you want at the end of part 1.

Next

Continue with part 2: the query, command, component and page that turn these tests green, then npm run verify, integration and mutation tests, and the commit.