phibac developer docs

Read another app's data

What you will do

You will build a second app, Note Board, that shows the pinned notes the user saved with the notes app from the quickstart. Note Board asks for the user's consent with requestAccess(), then reads the notes. It can only read them: access to another app's data is read-only.

A few words used on this page:

  • An app is a web app a developer builds. A user is the person who uses it; all their apps save into one private database that belongs to them.
  • A collection is one kind of data, such as notes, and each saved item in it is a record. The app that first published a collection owns it, and only that app can write to it.
  • Consent is the user's approval. To read a collection another app owns, your app needs the user's consent for that collection, which the user gives on a page of the server.
  • A major version is a numbered version of a collection's schema (the description of its fields). Records keep the major version they were written with, and a new major version can change fields in ways your code does not expect.
  • An origin is the start of a web address: http or https, the host and the port, such as http://localhost:5174.
  • Live updates are how the SDK (@phibac/sdk, the JavaScript library your page uses) tells your page that records changed.

Before you start

You need the notes app from Build your first app, finished, or as Upload and show files leaves it: the local server running in terminal 1 (npx phibac dev), the notes page served by Vite on http://localhost:5173 in terminal 2, and a few notes saved with Pinned ticked, in the browser you will use here.

You also need the name of the collection you want to read and its published major versions. Anyone can look up a published collection on the server, without a token:

curl http://localhost:8787/v1/schemas/com.example.notes.note

The answer is the latest published version, with its fields. After the quickstart and Upload and show files it is:

{"name":"com.example.notes.note","version":1,"minor":1,"description":"A note written by the user","fields":{"photo":{"type":"fileRef","description":"A photo attached to the note"},"pinned":{"type":"boolean","description":"Whether the note is pinned","indexed":true},"text":{"type":"string","description":"Note text","required":true,"maxLength":20000}}}

"version": 1 is the latest major version. Major versions are published in order without gaps, so every major version from 1 up to that number is published. To see an older major version, add ?major= and its number to the address, such as ?major=1 once the owner has published a version 2. Queries can filter and sort only on fields marked "indexed": true (and on createdAt and updatedAt), so Note Board can ask for the pinned notes.

Steps

1. Create the second app

Note Board is a separate app, in its own folder next to notes, with its own origin. Leave terminals 1 and 2 running: the notes app is needed later. Open a new terminal (terminal 3), go to the folder that holds notes and run:

mkdir board
cd board
npm init -y

Install the SDK, the CLI and Vite as in the quickstart:

npm install @phibac/sdk
npm install --save-dev phibac
npm install --save-dev vite

Create the app on the local server, with the origin Vite will use for it:

npx phibac init --name "Note Board" --origin http://localhost:5174

Keep the app ID it prints. Note Board has no collections of its own, so it needs no npx phibac deploy.

2. Describe the fields you read

npx phibac generate writes types only for the collections in your own pb.config.ts, and a collection another app owns cannot go there: npx phibac deploy would try to publish it and be refused. Write the type yourself, with only the fields your code reads, all optional. The owner may add fields later, and a record of another app may lack a field your code expects. You can also get the owner's full types from the server with curl "http://localhost:8787/v1/types?collections=com.example.notes.note@1".

3. Write the page

Create index.html in the board folder:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Note Board</title>
  </head>
  <body>
    <h1>Note Board</h1>
    <button type="button" id="sign-in">Sign in</button>
    <button type="button" id="show-notes" hidden>Show my pinned notes</button>
    <p id="message" role="alert"></p>
    <ul id="note-list"></ul>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Create src/main.ts, with Note Board's app ID in place of app_...:

import { connect, PbError, type Collection, type PbRecord } from "@phibac/sdk";

const APP = "app_...";
const BASE_URL = "http://localhost:8787";

// Another app's collection. Describe only the fields your app reads, all optional:
// the owner may add fields, and your app should not break when a field is missing.
interface Note {
  text?: string;
  pinned?: boolean;
}

const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const showNotes = document.querySelector<HTMLButtonElement>("#show-notes")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
const list = document.querySelector<HTMLUListElement>("#note-list")!;

let notes: Collection<Note> | null = null;
let stop: (() => void) | null = null;

function showError(e: unknown): void {
  message.textContent = e instanceof PbError ? `${e.code}: ${e.message}` : String(e);
}

// textContent shows text as typed: it never runs it as HTML.
function show(records: PbRecord<Note>[]): void {
  list.replaceChildren(
    ...records.map((record) => {
      const item = document.createElement("li");
      item.textContent = record.data.text ?? "(no text)";
      return item;
    }),
  );
}

// Reads the pinned notes. Fails with consent_required until the user allows it.
async function load(c: Collection<Note>): Promise<void> {
  try {
    show(await c.where("pinned", "==", true).get());
    showNotes.hidden = true;
    message.textContent = "";
    // Live updates: called again whenever a pinned note changes.
    stop?.();
    stop = c.where("pinned", "==", true).subscribe(show);
  } catch (e) {
    if (e instanceof PbError && e.code === "consent_required") {
      // No consent yet, or the user revoked it: offer the button.
      stop?.();
      stop = null;
      list.replaceChildren();
      showNotes.hidden = false;
      message.textContent = "Press Show my pinned notes to let this app read your notes.";
    } else {
      showError(e);
    }
  }
}

signIn.addEventListener("click", async () => {
  try {
    const backend = await connect({ app: APP, baseUrl: BASE_URL });
    // versions: the major versions of the collection this code understands.
    notes = backend.collection<Note>("com.example.notes.note", { versions: [1] });
    signIn.hidden = true;
    await load(notes);
  } catch (e) {
    showError(e);
  }
});

showNotes.addEventListener("click", async () => {
  if (notes === null) return;
  const c = notes;
  try {
    // requestAccess() opens a popup: call it first in the click, before any await.
    const granted = await c.requestAccess();
    if (granted) await load(c);
    else message.textContent = "You did not allow this app to read your notes.";
  } catch (e) {
    showError(e);
  }
});

What the code does:

  • backend.collection<Note>(name, { versions: [1] }) opens the other app's collection and lists the major versions your code understands. versions is required for a collection another app owns: without it the server refuses queries with invalid_request. Queries and live updates then give you only records of those versions. If the owner later publishes version 2, records written with it stay out of your results until you check that your code handles them and add 2 to the list.
  • The first query fails with consent_required until the user has given consent. The page then shows the Show my pinned notes button. Once consent is given it lasts, so on later visits the query works at once and the button stays hidden.
  • requestAccess() opens a popup on the server that asks the user. Call requestAccess() straight from a click, before any await: browsers allow a popup only then, and anywhere else it fails with popup_blocked. It resolves to true when the user allows, and to false when they deny or close the popup. Only one request can be open at a time.
  • After consent, the same query returns the notes, and subscribe keeps the list up to date as the user changes notes in the notes app.

SDK reference lists every way requestAccess() can fail.

4. Run it

In terminal 3, in the board folder:

npx vite --port 5174 --strictPort

5. Know what your app can and cannot do

Access to another app's collection is read-only: your app can never create, change or delete its records, with or without consent. A write is refused with forbidden. Because writes are queued, create, update and delete still return at once, and the refusal arrives later through backend.onConflict (see Offline writes and sync), when the SDK drops the change. Keep your own data in your own collections.

The same rule holds for files: your app can show a file of the other app's collection with files.url once it may read the collection, but it cannot upload files to it or delete them.

Consent covers the whole collection: every record, in every major version, including fields the owner adds later. Every read is shown in the user's activity log, and the user can revoke it at any time in their account area. From your app's next request on, reads fail with consent_required again and live updates for that collection stop. The code above then shows the button again the next time it loads. Do not call requestAccess() again by itself in a loop: if the user said no, show your app without that data.

What you should see

  1. Open http://localhost:5174 in the browser where you saved the notes and press Sign in. The first time, the popup asks you to connect the app: "Note Board (http://localhost:5174) will store data in your backend." Press Allow.
  2. The page shows Show my pinned notes and "Press Show my pinned notes to let this app read your notes."
  3. Press Show my pinned notes. A popup titled "Allow Note Board to read your data?" opens. Its first sentence is "Note Board (http://localhost:5174) wants to read your A note written by the user from Notes.": it names the collection with the description its owner wrote, and the owner by its app name. It then says that if you allow it, the app can read every entry in the collection, in every version, including fields Notes adds later, lists the fields it includes now (photo, pinned, text after Upload and show files; a field marked sensitive is shown with "(sensitive)"), and warns that the app could keep a copy of what it reads. The buttons are Allow and Deny.
  4. Press Deny. The page says "You did not allow this app to read your notes." Press the button again and this time press Allow. The popup closes and your pinned notes appear.
  5. In the notes app (http://localhost:5173), add a pinned note. It appears in Note Board without reloading.
  6. Open http://localhost:8787/account/activity: it lists Note Board's reads of com.example.notes.note. On http://localhost:8787/account/apps, under Access to other apps' data, press Revoke. Reload Note Board and press Sign in: the button is back.

Common problems

  • consent_required. The user has not given your app consent to read the collection, or revoked it. Call requestAccess() from a click, then query again.
  • invalid_request saying "versions are required to query" the collection. Open the collection with backend.collection(name, { versions: [1] }), listing the major versions your code understands.
  • version_unsupported saying the collection "has no published major version". versions names a version that was never published. Look up the latest major version with curl http://localhost:8787/v1/schemas/<collection>: every major version from 1 up to it is published.
  • forbidden saying your app "may not write to" the collection, through onConflict. Your app tried to create, change or delete a record of another app's collection. That is never allowed; save your own data in a collection your app publishes.
  • popup_blocked. requestAccess() was not called directly in a click or key handler, or the browser blocks popups for your site. Call it first in the click handler, before any await.
  • invalid_request saying "Another consent request is open". A consent popup for another collection is still open. Wait until its requestAccess() call resolves.
  • requestAccess() resolves to false. The user pressed Deny or closed the popup. Show your app without that data, and let the user press the button again if they change their mind.
  • invalid_request saying your app "owns" the collection "and needs no consent". Your app published this collection itself. It can read and write it without asking.
  • Records you saw before are missing. The owner may have moved them to a new major version that is not in your versions list. Check the published versions, and add the new one once your code handles its fields.

Next step

Change your schema safely shows how to change a published collection without breaking your app or the apps that read it, such as Note Board.