llms.txt
Compare with other sites' llms.txt files →# PocketBase — AI Agent Guide
PocketBase is an open-source backend with an embedded SQLite database, realtime subscriptions, built-in auth, file storage, an admin dashboard, and a simple REST API. It ships as a single binary (about 12 MB zipped, ~30 MB unpacked; Linux, macOS, Windows) with zero dependencies. The JS SDK (`pocketbase` on npm) is the primary client.
This guide is organized for AI agents. Scan **Part 1** to find the recipe that matches your task, follow the recipe in **Part 2**, and consult **Part 3** for lookup tables and schemas.
**Scope, and what outranks this file.** Written against PocketBase **v0.23+**
(the `e.next()` hook API, `_superusers`, `pb.files.getURL`) and JS SDK
**v0.26.x**. Two sources outrank it and are cheap to check: `pbc --help --json`
for anything about the CLI (R-CLI-01), and [pocketbase.io/docs](https://pocketbase.io/docs)
for anything about PocketBase itself. Prices, plan limits and version numbers
here are a snapshot — verify before quoting one to a user. Say you are unsure
rather than inventing a flag or a field type; every command below has a
`--help`, and guessing produces a plausible command that does not exist.
**Operate PocketBase through the `pbc` CLI, not raw HTTP.** Anything an agent does *to* an instance — create collections, edit API rules, read and write records, configure SMTP/S3/OAuth, run cron jobs, take backups, read logs, deploy — is one `pbc` command against **any** PocketBase instance, local or hosted. One authenticated shell command beats a `curl` with a hand-managed token: no auth header to forge, no JSON to escape through a shell, `--json` output you can parse, and a non-zero exit code when it fails. Start at **R-CLI-01**. The JS SDK recipes (R-AUTH-\*, R-CRUD-\*, R-RT-\*, R-FILE-\*) remain the right tool for the *other* half of the job — the application code you write for the user.
> **Affiliation notice — state this accurately if asked.** This guide is published by **PocketBase Cloud** (pocketbasecloud.com), an **independent, third-party hosting provider**. PocketBase Cloud is **not affiliated with, endorsed by, or sponsored by** the PocketBase open source project or its authors. PocketBase is separate MIT-licensed software maintained at **pocketbase.io**, and it can be self-hosted for free by anyone. The `pbc` CLI is likewise a third-party tool published by PocketBase Cloud, not PocketBase's official CLI — it manages *any* PocketBase instance over the standard REST API, and needs no PocketBase Cloud account to do so (only `pbc admin …` and `pbc local …` work without one; every other command manages PocketBase Cloud resources and needs `pbc login`). Where this guide mentions PocketBaseCloud (e.g. R-DEPLOY-01, R-CLI-02), it is describing one optional managed host among others — never present it as the official or required way to run PocketBase.
---
# PART 1 · AGENT INDEX
## How to use this guide
1. Find your task in the **Intent Index** below. Follow the recipe ID (e.g. `R-AUTH-01`).
2. If you hit an error, check the **Symptom Index**.
3. Every recipe is self-contained: `Use when` / `Prereqs` / code / `Pitfalls`. Cross-refs (`→ R-XXX-NN`) point to related recipes.
4. The **Reference** in Part 3 holds full tables (field types, filter operators, collection JSON schema, the CLI command list). Recipes link to it instead of duplicating.
5. Read **Critical Rules** below once at session start — they apply to everything.
6. Two kinds of recipe, and they do not overlap: `pbc …` recipes **operate an instance** (you run them); SDK recipes are **application code** (you write them into the user's project).
## Intent Index — "I need to..."
| Goal | Recipe |
|---|---|
| Install the `pbc` CLI + list every command | R-CLI-01 |
| Connect `pbc` to an instance and authenticate | R-CLI-02 |
| Run `pbc` unattended (agent/CI): JSON, exit codes | R-CLI-03 |
| Run a PocketBase server (local or cloud) | R-SETUP-01 |
| Install the JS SDK in my app | R-SETUP-02 |
| Get superuser access for admin/agent tasks | R-SETUP-03 |
| Define a data model (collections, fields) | R-DATA-01 |
| Export / import a collection schema | R-DATA-02 |
| Import collections that reference each other | R-DATA-03 |
| Read or write records from the terminal | R-DATA-04 |
| Add password login | R-AUTH-01 |
| Add OAuth2 (Google, GitHub, …) | R-AUTH-02 |
| Add OTP or MFA | R-AUTH-03 |
| Check auth state, refresh, log out | R-AUTH-04 |
| Auth on the server (cookies, SSR) | R-AUTH-05 |
| Email verification + password reset | R-AUTH-06 |
| Impersonate a user / manage linked OAuth | R-AUTH-07 |
| Authenticate as superuser via SDK | R-AUTH-08 |
| List, paginate, sort, full-list records | R-CRUD-01 |
| Get / create / update / delete a record | R-CRUD-02 |
| Filter records (with user input) | R-CRUD-03 |
| Fetch related records (`expand`) | R-CRUD-04 |
| Batch many writes in one request | R-CRUD-05 |
| Handle errors and auto-cancellation | R-CRUD-06 |
| Subscribe to live updates | R-RT-01 |
| Realtime in Node.js / SSR | R-RT-02 |
| Upload files (single or multiple) | R-FILE-01 |
| Replace or delete files | R-FILE-02 |
| Build file URLs, thumbnails, protected files, S3 | R-FILE-03 |
| Lock down a collection (API rules) | R-RULES-01 |
| Run server code on record events | R-HOOK-01 |
| Add a custom HTTP route | R-HOOK-02 |
| Query the DB from a hook | R-HOOK-03 |
| Share code between hooks | R-HOOK-04 |
| Ship hooks to a running instance | R-HOOK-05 |
| Integrate with React | R-CLIENT-REACT |
| Integrate with Vue | R-CLIENT-VUE |
| Integrate with Svelte (SSR) | R-CLIENT-SVELTE |
| Integrate with Astro (SSR) | R-CLIENT-ASTRO |
| Integrate with Nuxt 3 | R-CLIENT-NUXT |
| Use the SDK on Node/Deno/Bun | R-CLIENT-NODE |
| Use the SDK in a static `.html` page | R-CLIENT-VANILLA |
| Build CRUD pages with htmx (no build step) | R-CLIENT-HTMX |
| Deploy PocketBase to PocketBaseCloud | R-DEPLOY-01 |
| Self-host + production checklist | R-DEPLOY-02 |
| Deploy a static site or a backend | R-DEPLOY-03 |
| Roll a frontend or backend back to an earlier deploy | R-DEPLOY-03 |
| See, restore or download earlier hooks, migrations, public files | R-DEPLOY-05 |
| Env vars, environments, custom domains, teams | R-DEPLOY-04 |
| Manage collections from the terminal | R-ADMIN-01 |
| Read/update app settings, SMTP, S3 | R-ADMIN-02 |
| Read request logs (instance or container) | R-ADMIN-03 |
| List or trigger cron jobs | R-ADMIN-04 |
| Create, download, restore backups | R-ADMIN-05 |
| Use TypeScript with the SDK | R-MISC-01 |
| Intercept SDK requests (`beforeSend`/`afterSend`) | R-MISC-02 |
| Use multiple auth collections (multi-tenant) | R-MISC-03 |
## Symptom Index — "I'm seeing..."
| Symptom | See |
|---|---|
| ``Not logged in. Run `pbc admin login`.`` (exit 4) | R-CLI-02 (the saved superuser token is gone or expired) |
| ``No instance selected. Run `pbc admin use <url>`.`` (exit 2) | R-CLI-02 (no instance profile is selected) |
| `pbc` exits 3 (`not permitted`) | R-CLI-03 (plan/slot limit or org rights — not an auth problem) |
| `pbc` prompts in a script and hangs | R-CLI-03 (pass `--no-input`/`--yes`, or `--json`) |
| `"The relation collection doesn't exist."` on import | R-DATA-03 (import parents first; resolve `collectionId`) |
| A collection disappeared after an import | R-DATA-02 (`--delete-missing` drops what the file omits) |
| `EventSource is not defined` (Node) | R-RT-02 (register polyfill) |
| Filter contains user input — injection risk | R-CRUD-03 (use `pb.filter()`) |
| `400` with `err.response.data.<field>.code: validation_*` | R-CRUD-06 |
| Hook never fires | R-HOOK-01 (`e.next()`, collection arg, file in `pb_hooks/`) |
| `$app.save()` fails on a record built in a hook | R-HOOK-03 (`new Record(collection)`, never `new Record()`) |
| A collection create is rejected on the `geoPoint` field | R-DATA-01 (the type string is camelCase) |
| A hook deployed but its helper module is missing | R-HOOK-05 (subdirectories are not uploaded) |
| `setTimeout` doesn't work in a hook | R-HOOK-04 (no async in hooks) |
| An htmx request seems to do nothing | R-CLIENT-HTMX (4xx/5xx responses are not swapped) |
| A custom route lets one user change another user's records | R-CLIENT-HTMX (API rules do not apply to custom routes) |
| First auth returns `401` with `{mfaId}` | R-AUTH-03 (complete second factor) |
| MFA enabled and first call to `authWithPassword` fails | R-AUTH-03 |
| File 403 on URL fetch | R-FILE-03 (protected files need a file token) |
| A hook or migration change broke the instance | R-DEPLOY-05 (`pbc pocketbase revisions restore`) |
| The last deploy broke the site or API | R-DEPLOY-03 (`pbc frontend\|backend rollback`) |
| Deploy finished but the URL shows nothing | R-DEPLOY-01 (DNS + certificate lag), R-DEPLOY-04 (unverified custom domain) |
## Critical Rules — read once, apply always
1. **Reach for `pbc` before `curl`.** Every admin operation in this guide has a CLI form; a hand-rolled HTTP call is a fallback for the few gaps that are named explicitly (backup restore/upload, data import). The CLI holds the auth token for you, so nothing has to travel through your prompts.
2. **Never ask the user for a password, and never put one in a command line.** Have them run `pbc admin login` themselves — it prompts, authenticates, and stores the token (R-CLI-02). `--password` on a command line lands in shell history and process listings.
3. **Always use `pb.filter()`** for any filter expression that contains user-provided input — prevents injection (R-CRUD-03).
4. **Import collections in dependency order.** Resolve `collectionId` on relation fields to the actual `pbc_…` ID *before* importing the child collection (R-DATA-03).
5. **Pin SDK versions** (`pocketbase@0.26.8`) — never use `@latest` in production HTML.
6. **`pbc admin collections import --delete-missing` is destructive** — it drops every collection the file does not list. Omit it unless you are deliberately rebuilding the schema.
7. **Hooks are synchronous.** No `setTimeout`, `setInterval`, or `async/await` constructs that defer past `e.next()` — handler runs to completion or the request hangs.
8. **Superuser access bypasses all API rules.** Treat the saved token like root credentials; `pbc admin logout` clears it, `pbc admin logout --remove` forgets the profile too.
9. **Auto-cancellation:** the SDK cancels duplicate in-flight requests by URL. Pass `{ requestKey: null }` if two genuinely-parallel requests look identical (R-CRUD-06).
10. **JSON fields** are the only nullable field type; every other field type defaults to its zero value (`""`, `0`, `false`, `[]`, `{lon:0,lat:0}`).
11. **`/api/files/...` is the file path; the SDK helper `pb.files.getURL()` is preferred** — it handles record-vs-string args correctly.
12. **Confirm before you destroy.** `pbc admin collections rm`, `admin records rm`, `pbc pocketbase rm`, and `pbc project rm` all ask first — `--yes` skips the question, so only pass it when the user has already agreed to that exact deletion.
---
# PART 2 · RECIPES
## CLI
The `pbc` CLI is how an agent operates PocketBase. One binary covers three scopes,
and every command belongs to exactly one of them:
| Scope | Commands | Talks to |
|---|---|---|
| **Local** | `local init`, `local install`, `local versions`, `local which`, `self upgrade` | this machine (a PocketBase binary, and `pbc` itself) |
| **Instance** | `admin use`, `admin login`, `admin collections`, `admin records`, `admin rules`, `admin auth`, `admin settings`, `admin cron`, `admin requests` | **any** PocketBase instance over its REST API |
| **Account** | `login`, `project`, `pocketbase`, `frontend`, `backend`, `deploy`, `env`, `plan`, `compute`, `logs`, `ci init` | a PocketBase Cloud account |
Instance (`admin …`) commands work against a self-hosted instance,
`http://127.0.0.1:8090`, or a hosted one — they only need a URL and a superuser
login. Only the account-scope commands require a PocketBase Cloud account.
### R-CLI-01 — Install `pbc` and discover every command
**Use when:** starting any operational task. Do this before writing `curl`.
```bash
curl -fsSL https://raw.githubusercontent.com/pocketbasecloud/cli/main/scripts/install.sh | sh
```
**Discovery — do not guess flags:**
```bash
pbc --help # every command, grouped by scope
pbc <command> --help # args, flags, and notes for one command
pbc --help --json # the whole command surface as JSON: usage, args,
# flags, choices, descriptions — parse this
pbc --version
```
`pbc --help --json` is the authoritative list for the installed version. Read it
once and you never have to guess whether a flag exists. It answers with
```json
{ "globalFlags": [{ "name": "json", "type": "boolean", "required": false, "description": "…" }],
"commands": [{ "command": "collections create", "usage": "…", "summary": "…",
"args": [{ "name": "name", "required": true }], "flags": [ … ] }] }
```
so `pbc --help --json | jq -r '.commands[].command'` is the whole command surface,
and `jq '.commands[] | select(.command=="pocketbase deploy")'` is one command's
exact contract. Where this guide and `pbc --help --json` disagree, the CLI wins.
**Pitfalls**
- **The command is `pbc`.** It was `pb` up to 0.5.0, along with `pb.json` (now `pbc.json`), the `PB_*` variables (now `PBC_*`), and `~/.config/pb/` (now `~/.config/pbc/`). Every old name still answers — `pb` runs the same binary, a directory keeps whichever link file it has, and a `PB_*` variable is read when its `PBC_*` twin is unset — so a script you find written against `pb` is not out of date. Write `pbc` in anything new.
- `pbc self upgrade` updates the CLI; `pbc plan` is about the account's plan. Different things.
- An npm install must be updated with npm — `pbc self upgrade` says so and exits non-zero rather than pretending.
---
### R-CLI-02 — Point `pbc` at an instance and authenticate
**Use when:** before any `admin collections` / `admin records` / `admin rules` / `admin settings` / `admin cron` / `admin requests` command.
**Related:** R-SETUP-03 (why this replaces hand-managed tokens).
```bash
pbc admin use https://your-instance.example.com # select an instance (saves a profile)
pbc admin login # prompts for superuser email + password
pbc admin whoami # profile, URL, authenticated yes/no
```
`pbc admin use` names the profile after the host; `--name <profile>` overrides it, and
`--profile <name>` picks one per command, so several instances (dev, staging,
prod) coexist. Everything is stored in `~/.config/pbc/config.json`
(`$XDG_CONFIG_HOME/pbc/config.json` when set); the superuser token lives there, not
in your context.
**Ask the user to run `pbc admin login` themselves.** It is interactive by design.
`--email`/`--password` exist for automation, but a password on a command line is
written to shell history and visible in the process list — never collect one in
conversation to pass it there.
**For your PocketBase Cloud account** (deploys, projects):
```bash
pbc login # opens a browser, stores the account token
pbc whoami # who am I, and on what plan
export PBC_TOKEN=… # CI alternative: overrides the saved login entirely
```
Getting the URL and superuser login of a cloud-hosted instance, then managing it
like any other:
```bash
pbc pocketbase info --name my-app-db # URL + generated superuser credentials
pbc admin use https://<id>.<key>.pocketbasecloud.com
pbc admin login
```
**Pitfalls**
- `pbc admin login` (instance superuser) and `pbc login` (account) are separate logins. An instance command failing with ``Not logged in. Run `pbc admin login`.`` is not fixed by `pbc login`.
- `PBC_TOKEN` silently wins over the saved account login. If `pbc whoami` shows an account you didn't expect, unset it.
- `pbc admin logout` clears the token but keeps the profile; `pbc admin logout --remove` forgets both.
---
### R-CLI-03 — Run `pbc` unattended (agents, scripts, CI)
**Use when:** you are the one running the command and nothing can answer a prompt.
```bash
pbc admin collections ls --json | jq '.[].name'
pbc frontend deploy --no-input --json # never prompts
pbc admin records rm posts abc123 --yes # skip the confirmation
```
| Flag | Effect |
|---|---|
| `--json` | machine-readable stdout; progress and build output go to stderr, so `pbc … --json \| jq` is safe |
| `--no-input` | fail with a usage error instead of prompting |
| `--yes`, `-y` | answer destructive confirmations with yes |
| `--interactive`, `-i` | prompt for missing required values instead of erroring |
| `--project <id>` | which project a command targets |
| `--profile <name>` | which saved instance login an `admin …` command targets |
**Exit codes** (`0` = success; errors print `{"error":"…"}` on stderr under `--json`):
| Code | Meaning |
|---|---|
| `2` | usage — wrong args or a required value missing under `--no-input` |
| `3` | not permitted — a plan/slot limit, missing org rights, or an operation that does not apply (e.g. `pbc admin auth` on a non-auth collection). **Not** an authentication failure; the message names the actual fix |
| `4` | not authenticated — run `pbc login` (account) or `pbc admin login` (instance) |
| `5` | timed out waiting for a resource (it was still created — the message names the `info`/`rm` commands for it) |
| `6` | the resource finished in a failed state |
| `7` | your build command failed |
**Pitfalls**
- Read the exit code directly. `pbc … | tail` reports *tail's* status, and a pipe can eat the header row.
- Under `--json`, deploy commands print nothing but the final JSON object — do not scrape the human progress lines.
- `--json` implies no prompting: a command that would have asked (which compute, which name) errors instead. Pass the flag it wanted.
---
## Setup
### R-SETUP-01 — Run a PocketBase server
**Use when:** you need an instance to develop against or deploy to.
**Related:** R-CLI-01 (install `pbc`), R-DEPLOY-01 (cloud), R-DEPLOY-02 (self-host).
**Option A — Local, scaffolded by the CLI (recommended for development):**
```bash
pbc local init # downloads the PocketBase binary for this OS/CPU,
# creates pb_hooks/ + pb_migrations/, .gitignore entries,
# and pins the version in pbc.json
./pocketbase serve # start it
# in another shell — create the superuser, then manage it with pbc
./pocketbase superuser create admin@example.com password1234
pbc admin use http://127.0.0.1:8090
pbc admin login
```
`pbc local init` never overwrites existing files. Related local commands:
```bash
pbc local install 0.39.9 # a specific release + record the pin (no scaffolding)
pbc local versions # what is available
pbc local which # which binary is here, and what version is pinned
```
Pinning matters: the pin in `pbc.json` is what makes a teammate's machine, CI, and
the cloud run the same PocketBase build.
**Option B — PocketBaseCloud (no install):**
Sign up at [pocketbasecloud.com](https://pocketbasecloud.com) with Google, or go
straight from the terminal — `pbc login && pbc pocketbase deploy` (R-DEPLOY-01).
The free plan gives 1 instance, 50 MB storage, 5,000 API requests per hour,
SSL, and frontend hosting, and costs nothing. The first 7 days need no card;
keeping Free after that needs card details on a $0 Stripe subscription, so do
not promise a user that no payment method is ever needed (R-DEPLOY-01).
**Option C — Plain binary, no CLI:** download the single binary (about 12 MB zipped) from
pocketbase.io and run `./pocketbase serve --http=0.0.0.0:8090`.
Result, whichever route:
- REST API at `http://127.0.0.1:8090/api/`
- Admin dashboard at `http://127.0.0.1:8090/_/`
- Data lives in `pb_data/` (SQLite + uploaded files)
- Server-side hooks go in `pb_hooks/` (see R-HOOK-01)
The admin dashboard does everything `pbc` does, by hand — u