Define your data
What you will do
You will describe the data your app stores in pb.config.ts: its collections, their fields and the options that decide how the server checks and queries them. Then you will publish the description with npx phibac deploy and turn it into TypeScript types with npx phibac generate.
A few words used on this page:
- An app is the web app you build. A user is the person who uses it; the data your app saves belongs to that user, in their own private database on the server.
- A collection is one kind of data, such as notes, and each saved item in it is a record. A collection's schema is its description: what it holds and each field's name, type and rules. The server checks every record against it.
- Consent is the user's approval for an app to use their data. The pages where users give it are built from your schema, so what you write here is what users read.
Before you start
You need:
- A project folder with an app in it, created with
npx phibac init(the CLI, thenpx phibaccommand-line tool, which creates and changes your apps and schemas). Steps 1 to 4 of Build your first app set these up. - The local server running in another terminal (
npx phibac dev, run from the same folder).
This guide extends the notes collection from the quickstart. If you have not published it, that is fine: everything below works on its own.
Steps
1. Write the config file
Replace pb.config.ts with the file below, keeping the app value that npx phibac init wrote (your app ID, which starts with app_). It describes two collections: notes, with one field of almost every type, and comments on notes.
import { defineApp, collection, string, integer, boolean, datetime, enumOf, json, fileRef, recordRef } from "phibac";
export default defineApp({
app: "app_...",
collections: {
"com.example.notes.note": collection({
version: 1,
description: "A note written by the user",
fields: {
text: string({ description: "Note text", maxLength: 20000, required: true }),
pinned: boolean({ description: "Whether the note is pinned", indexed: true }),
color: enumOf(["yellow", "blue", "green"], { description: "The colour the note is shown in", indexed: true }),
priority: integer({ description: "Priority from 1 (low) to 3 (high)", min: 1, max: 3, indexed: true }),
remindAt: datetime({ description: "When to remind the user of the note", indexed: true }),
place: string({ description: "Where the user was when they wrote the note", maxLength: 200, sensitive: true }),
photo: fileRef({ description: "A photo attached to the note" }),
checklist: json({ description: "A checklist in the note: a list of items, each with a text and whether it is done" }),
},
}),
"com.example.notes.comment": collection({
version: 1,
description: "A comment the user wrote on a note",
fields: {
note: recordRef({ description: "The note this comment is about", indexed: true, required: true }),
text: string({ description: "Comment text", maxLength: 2000, required: true }),
},
}),
},
});
The file has one shape: defineApp({ app, collections }), where collections maps each collection's name to collection({ version, description, fields }), and fields maps each field's name to a field helper such as string({ ... }). version is the collection's major version; a new collection starts at 1. The steps below explain each part, and pb.config.ts reference lists every helper and option.
2. Name each collection
A collection's name is written like a reversed web address: com.example.notes.note. The rules:
- At least three parts separated by dots. Each part starts with a lower-case letter and uses only lower-case letters, digits and
-. - At most 128 characters in all.
- Names starting with
core.orsandbox.are reserved (see step 9). - The first app to publish a name owns it, and only that app can publish new versions of it or write records to it. Other apps can only read it, with the user's consent. On your own computer
com.exampleis fine; on a shared server, start with a domain you control.
3. Choose a type for each field
Each field helper gives the field a type, and the server accepts only values of that type:
| Helper | The field holds | Example value |
|---|---|---|
string |
Text. | "Buy milk" |
number |
Any number. | 4.5 |
integer |
A whole number. | 3 |
boolean |
true or false. |
true |
datetime |
A date and time as text in RFC 3339 form. Always write it with new Date().toISOString() (see below). |
"2026-11-14T09:30:00.000Z" |
enumOf([...], { ... }) |
One of the strings you list. | "blue" |
json |
Any JSON value: an object, a list, a number, a string and so on. | [{ "text": "eggs", "done": false }] |
fileRef |
The ID of a file your app uploaded with files.upload. |
"f_01JD..." |
recordRef |
Another record's global ID, which starts with pb:// (see Collections and records). |
"pb://u_01JC.../com.example.notes.note/0193a1f2-..." |
For a recordRef field the server checks only that the value starts with pb://; it does not check that the record exists.
Queries compare and sort datetime values as text, letter by letter. RFC 3339 allows several forms of the same moment (with or without fractions of a second, with a time-zone offset or Z), and mixed forms sort in the wrong order without any error: "2026-11-14T09:30:00Z" sorts after "2026-11-14T09:30:00.500Z". Write every value with new Date().toISOString(), which always gives UTC with milliseconds, so all values have one form.
Field names start with a letter and use only letters, digits and _, at most 64 characters. createdAt and updatedAt are reserved: every record already has them.
A record may hold only the fields its schema lists; a record with any other field is refused.
4. Write the descriptions
The collection and every field need a description: npx phibac deploy stops with an error that names the collection and field if one is missing or blank. Write them for a person, because people read them:
- The collection's description is how the consent page names your data when another app asks the user for permission to read it.
- Field descriptions become comments in the generated types, and they are part of the published schema, which other developers can read.
Say plainly what the data is ("Where the user was when they wrote the note"), not how your code uses it.
5. Set the rules each value must follow
These options make the server refuse a record whose value breaks them:
required: true: every record must have the field. Leaving it out, or setting it tonull, is refused. Fields without it are optional.maxLength(onstringonly): the most characters the text may have.minandmax(onnumberandintegeronly): the smallest and largest value allowed. Each one is optional.
A record that breaks a rule is refused with schema_violation, and the error lists each field and the reason.
Choose these rules carefully from the start. Making a field required, making a required field optional, adding or lowering a maxLength, adding or narrowing a min or max, and removing a value from an enumOf list are breaking changes: they need a new major version of the collection (see Collections and records).
6. Mark the fields you will query as indexed
indexed: true lets queries filter and sort on the field. A query can filter and sort only on indexed fields and on createdAt and updatedAt; any other field is refused with invalid_request. In the file above, notes can be filtered by pinned, color, priority and remindAt, and comments by the note they belong to.
A json field cannot be indexed. If you need to query part of it, store that part in its own string, number, integer or enumOf field.
Adding or removing indexed later is not a breaking change: publish it again and it takes effect.
7. Mark sensitive fields as sensitive
sensitive: true marks a field the user would consider private, such as a location or a health detail. When another app asks the user for permission to read the collection, the consent page lists the collection's fields and marks this one "(sensitive)", so the user can decide with that in mind. It does not change who can read the field: an app the user allows reads every field.
8. Publish and generate types
Publish the collections to the local server:
npx phibac deploy
npx phibac deploy checks the file, previews every collection, and publishes nothing if any of them has a problem or a breaking change. If you published the quickstart's notes first, you should see this (your app ID is different):
Previewing 2 collections for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.comment additive (will become version 1.0)
com.example.notes.note additive (will become version 1.1)
published com.example.notes.comment version 1.0
published com.example.notes.note version 1.1
Published 2 collections.
Adding optional fields keeps the notes in major version 1 and makes a new minor version, 1.1. Without the quickstart's notes, both collections become version 1.0.
Then generate the TypeScript types:
npx phibac generate
Wrote src/pb-types.ts (2 collections: com.example.notes.comment@1, com.example.notes.note@1).
src/pb-types.ts now holds one type per collection and SCHEMA_MAJORS, the major version of each collection your app writes. This is the whole file:
// Generated from published collection schemas. Do not edit by hand.
/** A comment the user wrote on a note */
export interface ComExampleNotesCommentV1 {
/** The note this comment is about */
note: string;
/** Comment text */
text: string;
}
/** A note written by the user */
export interface ComExampleNotesNoteV1 {
/** A checklist in the note: a list of items, each with a text and whether it is done */
checklist?: unknown;
/** The colour the note is shown in */
color?: "yellow" | "blue" | "green";
/** A photo attached to the note */
photo?: string;
/** Whether the note is pinned */
pinned?: boolean;
/** Where the user was when they wrote the note */
place?: string;
/** Priority from 1 (low) to 3 (high) */
priority?: number;
/** When to remind the user of the note */
remindAt?: string;
/** Note text */
text: string;
}
export const SCHEMA_MAJORS = {
"com.example.notes.comment": 1,
"com.example.notes.note": 1,
} as const;
Optional fields have a ?. A json field is unknown, so check its shape in your code before you use it. Pass SCHEMA_MAJORS to connect() and use the types for your collections, as this file does:
import { connect } from "@phibac/sdk";
import { SCHEMA_MAJORS, type ComExampleNotesNoteV1 as Note, type ComExampleNotesCommentV1 as Comment } from "./pb-types";
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
signIn.addEventListener("click", async () => {
const backend = await connect({ app: "app_...", baseUrl: "http://localhost:8787", schemaMajors: SCHEMA_MAJORS });
const notes = backend.collection<Note>("com.example.notes.note");
const comments = backend.collection<Comment>("com.example.notes.comment");
const note = await notes.create({ text: "Buy milk", color: "yellow", priority: 2, remindAt: new Date().toISOString() });
await comments.create({ note: note.id, text: "Semi-skimmed" });
});
A note's id is its global ID, the value a recordRef field holds. Run npx phibac generate again every time you change pb.config.ts and publish it.
9. Keep private data in a sandbox collection
For data only your app needs, such as settings or drafts, you can skip the schema. A collection named sandbox.<name>, such as sandbox.settings, needs no entry in pb.config.ts and no npx phibac deploy: use it straight away.
import { connect } from "@phibac/sdk";
interface Settings {
theme: "light" | "dark";
fontSize: number;
}
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
signIn.addEventListener("click", async () => {
const backend = await connect({ app: "app_...", baseUrl: "http://localhost:8787" });
const settings = backend.collection<Settings>("sandbox.settings");
await settings.create({ theme: "dark", fontSize: 16 });
});
A sandbox collection accepts any JSON object up to 256 KB, and the server checks none of its fields. It is private to your app: another app that uses the same name gets its own separate collection, and no app can ever be given permission to read yours. Because it has no indexed fields, queries on it can filter and sort only on createdAt and updatedAt. When data should be shareable with other apps, give it a schema and a real name instead.
What you should see
npx phibac deploylists each collection asadditiveand ends withPublished 2 collections.Run it again without changing the file and it says each collection issameand that there is nothing to publish.src/pb-types.tshas a type for each collection, with a comment from each description.- In your editor, TypeScript flags a value of the wrong type, such as
priority: "high"orcolor: "red", before you run anything.
Common problems
npx phibac deploysays "missing description". Add adescriptionto the collection or field it names. Nothing was published.npx phibac deploysays the collection name is invalid or in a reserved namespace. Use at least three lower-case parts, such ascom.example.notes.note, at most 128 characters, not starting withcore.orsandbox..npx phibac deploysays "json fields cannot be indexed". Removeindexedfrom thejsonfield and store the part you need to query in a field of its own.npx phibac deploysays a field name is reserved.createdAtandupdatedAtare system fields. Choose another name.npx phibac deployshows a collection asbreaking, with reasons such asfield removed: color. The server refused the change asschema_incompatible: it needs a new major version. Undo it, or raise that collection'sversionby one; see Collections and records.npx phibac deployfails withforbidden. Another app already owns the collection name. Use a name under a domain you control.- A write is refused with
schema_violation. The record does not match the schema. The error'sfieldslist names each field and the reason, such asrequired,longer than maxLengthorunknown field. Fix the data, or publish the schema change you meant to make. - A query fails with
invalid_requestsaying a field "cannot be used to filter or order". Mark the fieldindexed: true, runnpx phibac deployandnpx phibac generateagain. - A write fails with
not_foundsaying the collection "has no published schema". Runnpx phibac deployfirst, or use asandbox.name for data that needs no schema.
Next step
Sign users in adds a Sign in and a Sign out button and explains everything connect() does.