Build your first app
What you will do
You will build a small notes app: a web page where a user signs in, writes notes, and sees them update live. Everything runs on your own computer, on a local phibac server, and takes about 10 minutes.
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 the app saves belongs to that user, in the user's own private database on the server.
- A collection is one kind of data, such as notes. Each saved item in it is a record. The collection's schema lists its fields and their types.
- Consent is the user's approval: the first time a user signs in to your app, the server asks them whether your app may store data for them.
Before you start
You need:
- Node.js 22 or newer, with npm.
- A browser. You sign in to phibac with a passkey (a key kept on the device and unlocked with the device's screen lock, fingerprint or face; the browser must support passkeys) or with your email address and a password.
- The two packages: the SDK (
@phibac/sdk, the library your page uses) and the command-line tool, called the CLI (phibac), that you run in a terminal withnpx. Both are on the npm registry: step 1 installs them into your project, andnpx phibac …then runs the CLI installed there. CLI reference lists every command. - Nothing else for the local server.
npx phibac devruns a local server that comes with the CLI: installingphibacalso installs the server program built for your computer (macOS, Linux or Windows on x64, and macOS or Linux on arm64).
You will use two terminals: terminal 1 runs the local server, terminal 2 runs everything else. Once step 1 has made the project folder, run every command in it.
Steps
1. Create the project
In terminal 2, make a folder for the app and install the SDK, the CLI and Vite (a development web server that builds TypeScript; this page uses its commands):
mkdir notes
cd notes
npm init -y
npm install @phibac/sdk
npm install --save-dev phibac
npm install --save-dev vite
2. Start the local server
In terminal 1, go to the same notes folder and start the server:
npx phibac dev
It prints a line like this, followed by the server's log:
Starting /full/path/to/server/bin/pb-server (PB_MODE=dev, data in ./.pb, http://localhost:8787). Press Ctrl-C to stop.
The local server listens on http://localhost:8787 and keeps its data in the ./.pb folder inside the folder you started it from. It also adds a .pb/ line to .gitignore (and says so), so your test data never ends up in Git. Warnings in the log that backups are off and that no alert email is set are expected on your own computer. Leave this terminal running.
3. Create your account
Create the account you will sign in with in step 9:
- Open
http://localhost:8787/signupin your browser, type an email address and press Send me a link. Any address works: the local server sends no email. - It goes straight to the next page. Press Confirm and continue.
- On the page "Choose how to sign in", press Create a passkey and follow your browser's prompt, or press Set a password and choose one. You land on your account page.
If a page later asks you for a code from an email, such as when you sign in from a new browser, the local server shows that email in a box on the same page.
The CLI needs no token for the local server. A developer token is the secret key that lets the CLI create and change your apps and schemas (it can never read, write or export anyone's data), and the local server made its own when it started, in ./.pb/developer-token. The CLI uses it by itself. Keep that file secret: do not copy it, commit it or paste it into a chat.
4. Create the app
In terminal 2, create the app on the local server:
npx phibac init --name "Notes" --origin http://localhost:5173
--name is the name users see when they are asked for consent. --origin is the origin your page is served from: https or http, its host and its port, here the address Vite will use in step 9. The server lets an app be used only from the origins registered for it (or from http://localhost while you develop).
You should see:
Created app app_01M7E9YEJZZSYKAAB14AMBBJPR (Notes, origin http://localhost:5173).
Wrote pb.config.ts.
Next: define your collections in pb.config.ts (see the commented example), then run: phibac deploy
Your app ID is different. It starts with app_; keep it, you need it in step 8.
5. Describe your data
npx phibac init wrote pb.config.ts with your app ID and a commented example. Replace the whole file with this, keeping the app value that npx phibac init wrote:
import { defineApp, collection, string, boolean } 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 }),
},
}),
},
});
This describes one collection, com.example.notes.note, with two fields:
text, a string every note must have.pinned, true or false.indexed: truelets queries filter and sort on this field; the page in step 8 uses it to list the pinned notes.
Collection names are written like a reversed web address. The first app to publish a name owns it. On your own computer com.example is fine; on a shared server use a domain you control. Every collection and field needs a description: consent pages are built from them, for example when another app asks the user for access to your notes.
6. Publish the collection
npx phibac deploy
npx phibac deploy first previews every collection, and publishes nothing if any of them has a breaking change, such as a removed field. You should see:
Previewing 1 collection for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.note additive (will become version 1.0)
published com.example.notes.note version 1.0
Published 1 collection.
7. Generate types
npx phibac generate
You should see:
Wrote src/pb-types.ts (1 collection: com.example.notes.note@1).
The new file src/pb-types.ts holds a TypeScript type for a note and the version your app writes. This is the whole file as npx phibac generate writes it:
// Generated from published collection schemas. Do not edit by hand.
/** A note written by the user */
export interface ComExampleNotesNoteV1 {
/** Whether the note is pinned */
pinned?: boolean;
/** Note text */
text: string;
}
export const SCHEMA_MAJORS = {
"com.example.notes.note": 1,
} as const;
Do not edit it; run npx phibac generate again whenever you change pb.config.ts and publish it.
8. Write the page
Create index.html in the notes folder:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Notes</title>
</head>
<body>
<h1>Notes</h1>
<button type="button" id="sign-in">Sign in</button>
<p id="message" role="alert"></p>
<form id="note-form" hidden>
<input id="note-text" placeholder="Write a note" aria-label="Note text" />
<label><input type="checkbox" id="note-pinned" /> Pinned</label>
<button type="submit">Add note</button>
</form>
<h2>Pinned notes</h2>
<ul id="pinned-list"></ul>
<h2>All notes</h2>
<ul id="all-list"></ul>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
Create src/main.ts, and put your app ID from step 4 in place of app_...:
// src/main.ts
import { connect, PbError, type Collection, type PbRecord } from "@phibac/sdk";
import { SCHEMA_MAJORS, type ComExampleNotesNoteV1 as Note } from "./pb-types";
// The app ID that phibac init printed, and the local server that phibac dev runs.
const APP = "app_...";
const BASE_URL = "http://localhost:8787";
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
const form = document.querySelector<HTMLFormElement>("#note-form")!;
const noteText = document.querySelector<HTMLInputElement>("#note-text")!;
const notePinned = document.querySelector<HTMLInputElement>("#note-pinned")!;
const pinnedList = document.querySelector<HTMLUListElement>("#pinned-list")!;
const allList = document.querySelector<HTMLUListElement>("#all-list")!;
let notes: Collection<Note> | null = null;
// Shows an error's code and message. textContent shows text as typed: it never runs it as HTML.
function showError(e: unknown): void {
message.textContent = e instanceof PbError ? `${e.code}: ${e.message}` : String(e);
}
// Fills a list with notes. Each shows its status: "pending" until the server has it, then "synced".
function show(list: HTMLUListElement, records: PbRecord<Note>[]): void {
list.replaceChildren(
...records.map((record) => {
const item = document.createElement("li");
item.textContent = `${record.data.text} (${record.status})`;
return item;
}),
);
}
// connect() may open the sign-in popup, and browsers allow a popup only from a click.
signIn.addEventListener("click", async () => {
try {
const backend = await connect({ app: APP, baseUrl: BASE_URL, schemaMajors: SCHEMA_MAJORS });
notes = backend.collection<Note>("com.example.notes.note");
// Live updates: each function runs now, and again whenever the matching notes change.
notes.orderBy("createdAt", "desc").subscribe((records) => show(allList, records));
notes.where("pinned", "==", true).subscribe((records) => show(pinnedList, records));
signIn.hidden = true;
form.hidden = false;
message.textContent = "";
} catch (e) {
showError(e);
}
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const text = noteText.value.trim();
if (notes === null || text === "") return;
try {
await notes.create({ text, pinned: notePinned.checked });
form.reset();
} catch (e) {
showError(e);
}
});
What the code does:
connect()signs the user in and returns their backend. The first time, it opens a popup on the local server where the user signs in and gives consent. Call it from a click, as here, or the browser blocks the popup.backend.collection<Note>(...)gives you the notes collection, typed with the generatedNotetype..create()saves a note. It returns at once with the statuspending, and the note becomessyncedwhen the server has it. Without a connection the note waits in a queue and is sent when the device is back online..subscribe()calls your function with the matching notes, now and again whenever they change, including changes made in another tab or on another device.orderBy("createdAt", "desc")puts the newest note first;where("pinned", "==", true)keeps only the pinned notes, which works becausepinnedis indexed. A query returns at most 500 records unless you set another number with.limit(n); Query, sort and live updates explains queries.
SDK reference lists every function and method the SDK has.
9. Run the app
In terminal 2, start Vite on the port you registered as the origin in step 4:
npx vite --port 5173 --strictPort
Open http://localhost:5173 in the same browser you signed up with. Use localhost, not 127.0.0.1: they are different origins.
What you should see
- The page shows Sign in and two empty lists.
- Press Sign in. A popup from the local server opens. If you are not signed in to the server in this browser, it first asks you to sign in. Then it asks for consent: "Notes (http://localhost:5173) will store data in your backend." Press Allow. The popup closes and the note form appears.
- Type a note, tick Pinned and press Add note. The note appears under All notes and under Pinned notes, marked
(synced)once the server has it. - Open
http://localhost:5173in a second tab and press Sign in. This time the popup closes by itself, because this browser is already signed in to the app. Add a note there: it appears in the first tab too, without reloading. - Switch the browser to offline in its developer tools and add a note. It shows
(pending). Switch it back online and it changes to(synced).
The notes are saved on your local server, in the user's database, so they are still there after you reload the page and sign in again.
Common problems
npx phibac devsays the local server package is not installed. The packages were installed with--omit=optional(or--no-optional), which skips the server that comes with the CLI. Runnpm install --save-dev phibacagain without that flag. If it says there is no server package for your computer, see Develop on your own machine.npx phibac devstops with "address already in use". Another program, often an earliernpx phibac dev, is using port 8787. Stop it (Ctrl-C in its terminal) and start again.- Your account or app is gone. The local server keeps its data in
./.pbinside the folder you start it from. Startnpx phibac devfrom the same folder every time. npx phibac initsays "No local developer key found". The local server is not running. Startnpx phibac devin thenotesfolder (step 2), then run the command again in that same folder. If it says instead that a local server "was started in another folder", stop that server and startnpx phibac devin thenotesfolder.unauthorized: the developer token is invalid or revoked. The key in./.pb/developer-tokenno longer fits the server, for example after files in./.pbwere deleted by hand. Start again with empty data.npx phibac initsays "pb.config.ts already exists". You already created an app in this folder. Keep the file: itsappvalue is your app ID.npx phibac generatefails withnot_found: collection "com.example.notes.note" is not published. Runnpx phibac deployfirst, thennpx phibac generate.- Vite says "Port 5173 is already in use". Stop the other program on that port. If you use another port instead, the server asks for consent at every sign-in, because that origin is not the one you registered.
- The page shows
sign_in_cancelled. The popup was closed before sign-in finished. Press Sign in again. - The page shows
popup_blocked. The browser blocked the sign-in popup. Callconnect()only from a click, as the code above does, and allow popups forhttp://localhost:5173if your browser still blocks them.
Next step
Define your data explains every field type and option you can put in pb.config.ts, and the guides after it build on this notes app. To understand how users, apps and their data fit together first, read One backend, many apps.