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.jsonwith a manifest that lists the feature’s files. Kit modules live undermodules; your own features live underprojectModules. - Module definition: the feature’s
module.ts, created withdefineModule(...). - Module registry: the generated files
src/modules.generated.tsandsrc/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:
- Database port. If you changed
DB_PORTin.env, the port inDATABASE_URLmust match. - Migrations are committed.
git ls-files prisma/migrationsshould listmigration_lock.tomland theinitmigration. An empty result means migrations are ignored; see Database and migrations. - 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 insrc/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
navadds one menu item.iconis a lucide icon name, andorder: 50places it between Dashboard (10) and Users (80).routePrefixesis required by the type but does not protect the route. The page is protected byrequireModuleAccess("notes"), which you add in part 2.- Without
roles,adminOnlyorpublic, every role in the organization can access the feature. The optionalauditActions,apiScopesanduploadPurposesonly matter in projects with the audit logs, API keys or uploads modules. module.tsends up in the browser bundle through the menu, so it must not import server code.
src/features/notes/i18n/en.json
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:
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
- the entry key equals
manifest.name; - the name is not in both
modulesandprojectModules; - every module in
requiresexists inmodulesorprojectModules; filescontains a pattern starting withsrc/features/<name>/.
Run the generator again:
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 throughschemaRelations 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
Notemodel that does not exist yet, so any Prisma command that loads the schema fails withType "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: addschemaRelationsand run the generator. - After
prisma formator a manual edit.prisma formatwritesnotes Note[]below// wa:relations:end, outside the region. The next generator run adds the same line inside the region and the schema fails withField "notes" is already defined on model "Organization".Delete the line outside the region.
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 theNote model in its own schema file. Features never edit core schema files.
prisma/schema/notes.prisma
- Required
organizationIdwith an index and a relation toOrganization. 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 hasorganizationId, the kit’s runtime tenant-scope guard covers it automatically: afindManywithout an organization filter throwsTenantScopeError. See Organizations. onDelete: Cascade. Deleting an organization deletes its notes. The foreign key toorganizationsalso meansresetDatabase()in integration tests clears thenotestable, becauseTRUNCATE … CASCADEfollows foreign keys.@mapand@@map. Columns and tables usesnake_case, like the core.
migrate dev prints a Datasource "db": … line (check the database name and port there), then:
prisma/migrations/20261028044413_add_notes/migration.sql
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 dedicatedtest-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:"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.
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.requireModuleAccessreadsenv.MULTI_ORG, and the first read ofenvvalidates every core variable. The CIverifyjob has no.env, so the realenvwould fail there even though the test passes locally. - Errors carry a
digest.handleCommandErrorrecognizes a redirect by adigeststarting withNEXT_REDIRECT, just like Next.js. A mock withoutdigestwould turn the redirect into a default error message, and the test would check behavior the app doesn’t have.
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 missingorganizationId 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
redirectwith adigest. The core test’s stub throws a plainnew Error("NEXT_REDIRECT"). That is enough there, but a command that callsrequireModuleAccessinsidehandleCommandErrorwould turn it into a default error.- Mock
next/cache. Outside a Next.js request,revalidatePaththrowsInvariant: 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.
beforeEach:
src/features/notes/services/__tests__/notes-isolation.integration.test.ts
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):
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, thennpm run verify, integration and mutation tests, and the commit.