CLI
The protobase command comes with @protobase/cli. Install it globally, or in a project next to the packages its config imports:
bun add --global @protobase/cli # the protobase command for every bundled projectbun add --dev @protobase/cli @protobase/config @protobase/schema @protobase/layout @protobase/server @protobase/uibun run protobase <command> # from the project, config folder defaults to ./configbun run --cwd tests/apps/erp protobase <command> # in this repository, for an exampleListed in devDependencies, as the presets list them, or not at all, the packages make the project bundled: whichever CLI runs supplies them, so a global CLI runs a project with nothing installed. Listed in dependencies, they lock it to the installed copies. See Bundled and locked projects.
Any package manager installs it, and the command runs on Node or on Bun: npm install and npx protobase <command> work the same. The bin starts with #!/usr/bin/env node, so where Node is installed bun run protobase starts it on Node, unless the project’s bunfig.toml sets [run] bun = true, as the presets’ does. protobase --version (or -v) prints the Protobase version. Before any command runs, the CLI checks that the version specifier the current directory’s package.json lists the @protobase packages at holds its own version, and stops with an error naming both when it does not (see Versioning). That is the CLI’s one version check. Outside a project, or in one that lists no @protobase package, there is nothing to check. In a locked project that has its own @protobase/cli installed, a CLI installed elsewhere, globally, in CI or in an image, hands the command over to that one before anything else, with a line on stderr naming its version, so the project runs on the version it is locked to.
How it runs
Section titled “How it runs”The published @protobase packages are JavaScript: each is built with tsdown to ES modules and type declarations in dist, one file per source module, and packing them points their exports, types and bin at it (publishConfig). The installed protobase command (bin/protobase.mjs) runs dist on Node 22.12 or later, or on Bun. The commands that read the project’s own TypeScript, such as users and doctor, import it directly on Bun and through Vite’s module runner on Node, which cannot resolve its extensionless imports; dev serves it with Vite and build bundles it.
In this repository nothing needs a build: the packages’ exports point at src, and the workspace’s protobase is bin/protobase-source.mjs, which imports src/index.ts: Bun loads it itself, Node through tsx. bun run build builds every package to dist.
In another process
Section titled “In another process”A process that runs many commands, such as a deploy, can run them without starting the CLI each time. @protobase/cli/runner exports one function for that; @protobase/cli/auth exports the other one a script may call, loadProjectAuth, which builds the project’s sign-in as the users commands do (see Auth). @protobase/cli/scaffold is scaffold as functions, for npm create protobase <database-url>, which loads it from the project it installed: listTables, runScaffold and asking, its column prompt on a question function of the caller’s. Nothing else of the CLI is exported:
import { runCommand } from '@protobase/cli/runner'
const { exitCode, stdout, stderr } = await runCommand(['doctor', '--env', 'DATABASE_URL'], { cwd: '/srv/app', env: { DATABASE_URL: url } })cwdis the folder the command runs in, andenvits whole environment, as a child process gets them. Both default to the current process’s.stdinis what the command reads from stdin, by default nothing.- Commands run one at a time, since they share the process’s working folder, environment and output. Each puts them back when it ends.
- The CLI and its packages stay loaded, so only the first command pays for loading them. On Bun the project’s own files are loaded again for each command, so a command sees them as they are when it starts.
dev,serve,workerandmobilerun until a signal, so the runner refuses them; start them as a process.- A command that ends with an exit code returns it rather than ending the process. Database pools a command opens for the project close once idle.
The serve runtime is bundled by protobase build-serve into one JavaScript file for Bun, so production needs neither node_modules nor the CLI (see serve).
scaffold and doctor read the database with default_transaction_read_only = on, so they can never write, and so does dev’s check of the connection. The commands that manage the app’s data do write: users, organizations, encryption apply, files cleanup and import supabase.
scaffold
Section titled “scaffold”protobase scaffold [connection string | --env VAR] [target] [options]Without a connection string or --env, the URL is DATABASE_URL, from the environment or the nearest .env at or above the current directory, as dev reads it. target is all (default), schema, schema.table or schema.table.column. Tables are introspected from pg_catalog; config/<resource>/data.ts is created or extended. A table that a written one points to with a foreign key is written too, outside the target or excluded, unless it has a resource already, since the app refuses a relation to a resource it does not have; a line names each.
Protobase’s own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the auth schema or another schema with the store’s auth_migrations table, or with Better Auth’s session, account and verification tables whose sessions point at a user table (in public, only the tables of the store’s migrations and that user table, whatever it is called), pg-boss’s jobs schema, and the migrations schema whose applied table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the jobs or migrations schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and dev and serve refuse to start with a resource over the auth store.
| Option | Effect |
|---|---|
--env <variable> |
read the connection string from this variable instead of DATABASE_URL |
--config <dir> |
config folder, default config |
--yes |
accept every proposal, no prompts (required without a TTY) |
--dry-run |
print a diff, write nothing |
--ui |
also write ui.ts (.names() and .list()); the list never shows a secret-like column (password, hash, token, secret, salt, otp, private_key, api_key in its name) |
--ui-list, --ui-section <names|list> |
write only those ui.ts sections |
--exclude <schema[.table]> |
skip tables, repeatable |
npm create protobase <database-url> runs it in the project it makes, on the tables you pick there (see On an existing database).
Interactively, each new column shows its proposal: accept, accept all (this one and every one after it, without asking), edit (name, type) or ignore (writes field: null; key columns cannot be ignored).
The list --ui writes shows five columns at most: the key unless it is a uuid, up to two relations, then the other fields but long text, json and audit timestamps. It sorts newest first by a sortable created_at (or inserted_at, createdAt, …), else by another sortable date or timestamp, else not at all.
Inference
Section titled “Inference”| Database | Field |
|---|---|
int2, int4 / int8 |
f.integer() / f.bigint() |
numeric(p,s) |
f.decimal({ precision, scale }) (unconstrained: 38, 9) |
text, varchar, bpchar |
f.text() |
bool, date, timestamp(tz), uuid, json(b) |
f.boolean(), f.date(), f.timestamp(), f.uuid(), f.json() |
Postgres enum, or a CHECK (col IN (...)) on text |
f.enum([...]) |
| foreign key | f.relation('<resource>'), .columns([...]) for a composite key (on its first column) |
anything else (ltree, arrays, …) |
f.text().readOnly() |
NOT NULLabsent:.optional(). Literal default:.default(v).- Computed defaults (function, sequence, expression,
GENERATED BY DEFAULTidentity):.dbDefault(). It also gets.readOnly()when the column is an identity column, a primary-key column, or an audit timestamp (created_at,inserted_at,updated_at,modified_at, or the same in camelCase, such ascreatedAt); other computed defaults, such asorder_date DEFAULT current_date, stay editable.GENERATED ALWAYSidentity and generated columns are only.readOnly(). - Leading column of a non-partial index:
.filterable(); of a btree: also.sortable(). Not applied to json. - The text field that names a record (
name,title,number,sku,email,codeordescription, else the first text field) becomes the resource’s.search(...)when a non-partial pg_trgm index (gin_trgm_opsorgist_trgm_ops) serves it, so the global search finds its records by name. Without one the API would refuse the search, so it is left out; add the index and runprotobase scaffoldon a new resource, or add.searchby hand. - Key: primary key (composite supported), else the first unique index with only
NOT NULLcolumns, else the table is skipped with a warning.A table that points to a skipped table without a key cannot start, as writing its foreign key as a plain field instead of a relation is not implemented; A view or materialized view is skipped with a warning too, as Postgres knows no key for it: declare a resource over one by hand.doctorreports the relation. deleted_at,removed_at,archived_at(nullable timestamp/date) become.softDelete;organization_idandtenant_idbecome.tenant.- Unique indexes are listed in the doc comment above the resource.
- Field names are the column names in snake_case;
.column()is written only when the schema builder’s default mapping would not give the column back (always forhr."EMP_MASTER"). - Resource names are the table name in snake_case, prefixed with the schema on collisions, and exported under their camelCase name (
export const orderLines = resource('order_lines')). Names already inconfig/win.
Re-running
Section titled “Re-running”Existing data.ts files are edited with ts-morph: only columns that are neither declared nor null are added, at the end of .fields({...}). Nothing else is rewritten, and key, soft delete and tenant calls are only written when a resource is created. ui.ts gets only missing sections. config/index.ts gets exports for resources created in the run (all resources when it does not exist yet), each table after the tables its foreign keys point to and otherwise by name, so the sidebar, and the table the app opens on, start with tables others refer to; existing lines are never touched. A run with nothing new changes nothing. schema.table.column on an unscaffolded table scaffolds the whole table.
Drift report
Section titled “Drift report”After each run, declared fields are compared with the database: a column that no longer exists, a type that no longer fits (a relation fits integer/bigint/uuid/text, currency and country fit text), or different enum values. Each entry carries a suggested replacement. Drift is reported, never applied.
doctor
Section titled “doctor”protobase doctor [connection string | --env VAR | --without-database] [--config <dir>]The URL comes as for scaffold: the connection string, the variable --env names, or DATABASE_URL, each also read from the nearest .env.
A config that exports no resource fails, as one that lost its resources by mistake, unless protobase.config.ts says the app has none with resources: 'none'; one that says so and exports a resource fails too.
Imports config/index.ts and the views of config/*/ui.ts, as the config module has them by convention, and checks every exported resource against the database, with the resources Protobase adds by what protobase.config.ts (read with command: 'tool') and the resources enable: the webhook ones of webhooks, Failed jobs, Activity and Comments. The tables migration writes for those have every index their reads need, so after the project’s migrations they pass; a read of theirs that lacks an index, as on a table an earlier version wrote, is an error and doctor exits 1 until you run migration and apply what it writes:
-
error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index,
.openExisting()fields that are not the columns of a unique index, relation to a resource the config does not declare, a lookup field of the one record of another resource without a unique index on the relation it reads that record by -
error: a read the scan guard refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table’s indexes from the catalog, as the server does, and judges with the scan guard’s own rule every read the API takes and the app makes: a filter on each
.filterable()field, a sort by each.sortable()one,search()over the search fields, a role’s own records (.owner()), the names a relation shows and the linked records a lookup field reads, judged against the linked table; each view’s list in its order and with the filter it opens with, its filter widgets and their counts, its chart, its map, board, calendar and timeline, its card photos, its order by hand, its related sections, galleries and charts, its named lists, its recent records and a saved search’s new records; and each read of a composed page’s read plan: its blocks’ lists, counts and aggregates, aChart’s grouped and split fields, a nested list’slimit_per, and the outer read eachrelated()term carries with its own filter and order. Each error is an index to add, with every request that needs it and where it comes from:error agencies: no index serves the column "name", so the API refuses:GET /agencies?order_by=name asc ("name" is sortable; the agencies list's order)fix: create index on "market"."agencies" ("name");Reads are judged as the scan guard’s default
rejectmode judges them, for a role that reads every row, such as admin; other access rules are code doctor does not run. A resource on a plain view or a foreign table is not judged, as the scan guard does not judge it. -
error: a read of those that sorts by a field that is not
.sortable(), which the API refuses with a400whatever the indexes: a list’s order, from its view’ssortor the order the app picks itself, such as a calendar’s or timeline’s start, a recent-recordsorderBy, a related section’s, gallery’s or page block’ssort. One error per field, with every request that sorts by it:error seller: name: not sortable, so the API refuses:GET /seller?order_by=name asc (the seller list's order)fix: mark "name" .sortable() in data.ts, or sort the list by a sortable field -
warning: a file field whose column no index looks files up in, so each file cleanup reads every row of the table before it deletes a file. The fix is an index on the file without its query part, which a partial index cannot be, as soft-deleted rows still hold their files:
warning photos: no index looks up the files of "photo", so each file cleanup reads every row of the table to check that none holds a file it deletesfix: create index on "photos" ((split_part("photo", '?', 1))); -
warning: enum values differ
Doctor also lists, as a note it does not count, each custom component of a page that declares no reads, since it reads outside the page’s plan.
When the config has no errors, doctor then builds the app from protobase.config.ts and its own config folder, whatever --config names, as serve does and runs the server’s startup checks of the database, and stops with the server’s own message at the first one that fails: an auth store behind this version, a resource over a table of the auth store, events, history or live updates without their triggers, a missing comments table, rollup and formula fields without their columns or triggers, and a jobs, webhooks, workflows, notifications, status or user tables schema that is missing or behind. A change that passes doctor so starts. Sign-in is built only to read its store, so doctor needs neither PROTOBASE_URL nor PROTOBASE_SECRET. The one startup check doctor leaves out is the model key of AI fields and actions, which belongs to the environment the app runs in.
Without a connection string, --env or DATABASE_URL, doctor stops and names --without-database. With that flag it connects to nothing and checks what the project alone tells:
| Check | Without a database | With one |
|---|---|---|
Relations to a resource the config does not declare, sorts by a field that is not .sortable(), page components without reads |
yes | yes |
The triggers, capture(), outbox, history and notices tables of resources with events, history or live updates |
from db/migrations/*.sql, for each resource whose table a migration creates |
from the catalog |
| The server’s build of the app, such as an owner field that must hold sign-in’s user ids | yes | yes |
| Tables, columns, types and keys; indexes for the reads; user tables; the other startup checks of the database | skipped | yes |
From the migrations, a resource passes when they create its table, capture() in the changes schema and the outbox, the history table when it keeps history and the notices table when it is live, and a trigger of each name the server looks up on its table; a missing one fails with the server’s message, as the startup check does. Statements are matched by name in the files, in any order, so a trigger a later migration drops or one created in dynamic SQL is judged only with a database. A resource whose table no migration creates, as in an app on a database of its own, is left to the database.
Skipped without a database: the tables, columns, types and keys of the resources, and the indexes their reads need the server's startup checks of the database's schemas, but for the change capture of the resources whose table a migration creates the change capture of notes, whose table no migration createsExit code is 1 when there are errors. Run it after the project’s migrations and before a new version serves, as a platform’s deploy does: a read it fails is one the API would refuse once the version runs. protobase build needs no database, so the indexes are doctor’s to check.
protobase eject [connection string | --env VAR] <table>... [--config <dir>] [--dir db/migrations]Takes tables users added over as code. The URL comes as for scaffold. For each table named, as its definition names it, it writes config/<table>/data.ts and config/<table>/ui.ts with scaffold’s renderers, exports them from config/index.ts, and writes one migration in --dir, NNN_eject_<tables>.sql. It only reads the database.
data.tsis a resource of the same name overuser_tables.<table>, where the table stays: the fields of the definition as the server serves them, filterable, sortable and searched where the table’s indexes serve them, a text field at most 500 characters, and every operation the admins’ alone, with.explicitGrants(). A column the definition has no field for is written asfield: null.ui.tshas the definition’s singular and plural label, its title field, each field’s label, a long text field multiline, and the listscaffold --uiwrites.- The migration makes each table as the catalogue has it:
create schema if not exists,create extension if not exists pg_trgmwhen an index needs it,create table if not existswith the columns and constraints, andcreate index if not existsfor each index, by its name. On the database the table is in it changes nothing and moves no row; on an empty one it makes the same table.
Then it runs doctor on the config. When doctor reports an error in an ejected resource, or cannot load the config, every file is put back as it was and the command fails. It refuses a name no definition the server serves has, saying why the server leaves it out, and one a resource in config/ has, or whose table one reads, already. It refuses a table that belongs to an organization, which scaffold takes over instead.
protobase eject notes # config/notes/data.ts, config/notes/ui.ts, db/migrations/NNN_eject_notes.sqlDeploy the change soon: until it serves, the admin app still adds fields to the table, which the new config does not have. Once it has deployed, migration writes the delete of the definition (see Taking a table over as code).
protobase dev [--port <port>] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-hosts <hosts>] [--extend <dir>] [--no-jobs] # run inside a project, e.g. bun run --cwd tests/apps/erp devprotobase dev --api <url> [--port <port>] [--cache-dir <dir>] [--allowed-hosts <hosts>] [--extend <dir>] # the UI alone, on the API at <url>One port, two processes: Vite serves the admin app from @protobase/ui’s src/app/ (dist/app/ when installed; index.html and main.tsx, or main.js; the command fails with a clear message when they are missing) and hands /api, supabase-js’s /api/sb included, to the Hono app from createAdmin, which runs in a process of its own; the CLI’s process never loads @protobase/server. Open http://localhost:<port>; the API reference is at /api/docs.
-
Server package: in a locked project, whose
package.jsonlists the@protobasepackages independencies, the API’s process loads@protobase/serverfrom the project’snode_modules; one that is not installed fails as with any missing package. A bundled project, which lists them indevDependencies, lists none or has nopackage.json, gets the CLI’s own copies of every package the serve runtime supplies, the@protobasepackages,kysely,pg,reactand the rest of the list, for its files too, whatever it installed; its page code’s imports of the@protobasepackages, React and React DOM get the admin app’s own copies. -
Secret: a
PROTOBASE_SECRETstill set to the placeholder of.env.example(change-me-...) prints a warning once the server is ready, asservedoes at start: anyone who knows it can sign session cookies. -
Database: the URL comes from the variable named by
--env, read from the environment or the nearest.envat or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to itsdb:upscript when it has one). The API connects with Kysely over thepgthe config gets: the project’s own when it is locked, the CLI’s when bundled. -
Port: each project keeps its own port on this machine, in
.protobase/dev-port, so its address and bookmarks stay the same from run to run. The first run without--portpicks a random port from 10000 to 49151 that is free on both loopback addresses and keeps it;--port <port>serves on that port and keeps it for the runs after, so one run with--portchanges it. The app listens on both127.0.0.1and::1, sincelocalhostis either one depending on the runtime and the browser. When another process holds the port on either address the command stops before it starts and names that address; stop the other server or run once with another--port. With aPROTOBASE_URLon this machine at another port, sign-in refuses the app’s pages, so the command warns once it is ready; unset, the app’surlis the dev server’s own address. -
Cache: Vite’s dependency cache is
node_modules/.vite; two dev servers sharing it can disturb each other’s optimisation, so pass--cache-dirfor a second one (the integration test does). -
Login: real sign-in only, with the config’s
auth, on by default, or itsauthenticatefor tokens of an auth server elsewhere (see protobase.config.ts and Login with Better Auth). A project with sign-in off and no authenticator fails at startup with a message pointing there, as does one with sign-in on and noPROTOBASE_SECRET, one whose auth store has not applied every migration of this version, naming them (seeauth migration), one with a resource over a table of the auth store, and one with a resource whose events or history lack their triggers, or whose comments lack their table, or whose rollup and formula fields lack their columns or triggers, which it checks again on every reload (seemigration), and one with an AI field or action and no model key; there is no development login. Theloginline of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such asbun run protobase users create [email protected] --generate-password(the package manager that starteddev,npxotherwise). Against a database that has users already, such as an app’s hosted one, sign in as one of them or add one with a new email; its own password is set there. Awarningline follows for each way the auth store’s tables differ from what the app’s sign-in needs, such as a column dropped by hand: the one place Protobase compares them, sinceservereads the store’s record of migrations alone. -
Mobile releases: see below.
-
Jobs: with jobs in the config it runs them in the API’s process, once the jobs schema checks out (see
migration); an edited job runs its new code from the next job on.--no-jobsruns none of them and delivers none of the app’s events, webhooks or pushes, for a dev server on the database of a hosted app that already runs them; jobs are still enqueued, for that app to run, and the startup message saysjobs off. -
Realtime relay: with
realtime.relayand nourl, it runs the relay from@protobase/realtime, the project’s install or else the CLI’s, for the app, gives the app its address and keys, and stops it with the dev server (see Local development). -
Tunnels and other hosts: Vite only answers
localhostby default.--allowed-hosts .trycloudflare.com,app.example.comadds Host headers (a leading dot matches all subdomains). The API’s WebSockets, such as an API function’s, pass the same check: an upgrade with another Host header is refused with403. Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects overwsson 443 as long as the tunnel forwards WebSockets. -
Project discovery, by convention:
config/index.tsexports the resources (and views), and everyconfig/*/ui.tsexport that is not already exported by the index is added as a view. Eachfunctions/<name>.ts(orfunctions/<name>/index.ts) is an API function at/api/functions/<name>.protobase.config.ts(orprotobase.config.json) in the project root describes the rest as data, and the jobs, hooks and other code it names are found by their paths; see protobase.config.ts. Without it, the app runs on the defaults. -
Project UI: the app imports
protobase.ui.tsxfrom the project root, with hot reload, when it exists (see Custom components): the same contract as the pluginprotobase buildmakes of it, built into the dev page instead. Layout files are checked as they load, asprotobase buildchecks them. -
Theme: the page links
/protobase.theme.css, which the dev server answers from the project’s theme, checked as the build checks it, on every request, so an edit shows on the next reload. It links/protobase.favicon.svgtoo, the project’s favicon or a neutral mark, and/protobase.apple-touch-icon.png, which it answers with the PNG icons the project has. -
Extensions:
--extend <dir>merges an extension in, its UI built into the dev page beside the project’s, to try one out; its files reload like the project’s. -
Hot reload: server code, data configs,
ui.tsviews, layouts and the config are loaded through Vite’s SSR module graph, and the config is read again with each rebuild. A change inside the project (or, in this repository, inpackages/server,packages/query,packages/schema) rebuilds the API on the next request without a restart;/metaandX-Meta-Versionchange, so open tabs refetch. The database pool survives reloads. Newly addedui.tsfiles appear after the next change inside the project.
UI only
Section titled “UI only”--api <url> serves the admin app with the project’s UI, theme, icons and --extend folders, hot reloaded as above, and hands every request the API process would answer (/api, /.well-known/webauthn, the OAuth discovery documents and /protobase.sw.js), its WebSockets included, to the Protobase app already running at <url>, such as https://staging.example.com or another protobase dev. Nothing reads a database or the project’s config: no DATABASE_URL, no PROTOBASE_SECRET, no migration checks and no jobs, and resources, roles and data are the instance’s. Change the UI here and the server code where the instance runs.
- Checked at start: the instance must answer
/api/metawith anX-Meta-Versionheader, as every Protobase app does; otherwise the command names the URL and what came back.<url>is an origin, without a path. - Sign-in: sign in as a user of the instance. Requests from the dev server’s own pages reach it with its own Host, Origin and Referer, so its origin checks pass; a request from any other site keeps its own origin, which the instance refuses. Its cookies come back without their
Domain, forlocalhostto keep, and a redirect to its own address becomes a path on the dev server.
Extending a config
Section titled “Extending a config”--extend <dir> (repeatable) merges an extension’s folder into the app before the project: its config and the code its paths find, the same as the project’s. How each part merges, and what a name defined twice does, is in Extensions.
protobase build [--out dist] [--bun] [--extend <dir>] [--source-maps] [--strict] # run inside a project, e.g. bun run --cwd tests/apps/erp protobase buildWrites the project’s deploy bundle, the folder a deployment ships:
dist/ protobase.config.js the config module for serve migrations/ the project's db/migrations/*.sql, which the runtime's migrate applies; only with some node_modules/ the packages it loads from disk, only when it imports native add-ons public/ index.html, assets/ the admin app: the shell, the same for every project protobase.sw.js the shell's service worker (see Installable app) plugins/app/ the project's protobase.ui.tsx, built as a plugin plugins/<extension>/ each --extend folder's protobase.ui.tsx, built as a plugin protobase.theme.css the project's theme, checked and minified; empty without one protobase.favicon.svg the project's favicon; a neutral mark without one protobase.*.png the project's PNG icons, the ones it has (see App identity) protobase.bundle.json the manifestThe output folder is not emptied; public/, migrations/ and node_modules/ are replaced on every build. migrations/ and node_modules/ are deleted only when the previous build’s manifest names them, so a build into a folder with a project’s own node_modules fails instead. Of the project’s server code only the config folder runs at build time, config/index.ts and config/*/ui.ts with what they import; the build reads protobase.config.ts (with command: 'build') but builds nothing it describes, so it needs no secrets and no database. It is loaded once in Node to check each view against its resource: a filter widget or the chart on a field that is not .filterable(), a list sorted by one that is not .sortable(), or a list search on a field outside the resource’s .search(...) fails the build, naming the view and the field, since the API would refuse it once a page asked. Whether an index serves those reads needs the database, which doctor checks. Its browser code is loaded once in Node too: to check its component names (see The UI) and to read the field types each plugin registers.
A token the theme sets that the app does not read prints a warning: line, a likely typo; the build still succeeds.
By default the bundle runs on Node and on Bun. --bun makes it a bundle for Bun only, as the Protobase images and the cloud serve it: Bun’s bundler writes the config module (see the config module), so the build needs bun on PATH and fails without it.
Source maps
Section titled “Source maps”--strict fails the build on what it otherwise warns of in the config folder’s layouts: a bare name that more than one record around it has, which reads the nearest (see Paths and scopes).
--source-maps writes a source map beside each script of the shell and the plugins, assets/<name>-<hash>.js.map, for an error tracker to read the browser’s stack frames with. Each script ends with a //# debugId=<uuid> comment, and its map carries the same debugId; the scripts name no map, but a host serves the maps with the rest of public/ unless it moves them out. The shell’s maps come prebuilt in @protobase/ui’s dist/shell-source-maps/. Without the option the bundle has no maps. build-plugin --source-maps does the same for a plugin built on its own.
Extensions
Section titled “Extensions”--extend <dir> (repeatable) adds an extension to the bundle without touching the project’s files: a folder with a protobase.config.ts, a protobase.ui.tsx or both. Its config and the code its paths find go into the config module beside the project’s, merged before the project’s own when the bundle is served, in the order given (see Extensions). Its protobase.ui.tsx becomes one more plugin of the bundle, in public/plugins/<name>/, named by its package.json’s name, else its folder’s. A host adds its own widgets, dock assistant tools (assistant/tools.ts) and MCP tools (mcp/tools.ts) to every app it builds this way; to add React code to apps without building them, serve a plugin instead.
- The extension’s imports of
@protobase/*resolve from the project, so it runs on the app’s own versions;react,react-domand@protobase/uiare the app’s at runtime, as for every plugin. Everything else it imports resolves from its own folder and is built into its plugin, with a stylesheet of the classes its files use. - A component, action handler or field type that the extension and the project both define fails the build, naming both. To find them, the build loads the merged UI configs once in Node: only browser code, which needs no secrets. Its server code does not run at build time, so an assistant or MCP tool both define fails when the bundle is served, naming both.
- An error names an extension by its folder. Two extensions whose plugins would have one name fail the build.
The manifest
Section titled “The manifest”protobase.bundle.json is the contract between a bundle and the host that serves it:
{ "version": 3, "protobase": "0.12.0", "server": "protobase.config.js", "public": "public", "spa": "index.html", "api": ["/api", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/openid-configuration"], "theme": "protobase.theme.css", "plugins": [ { "name": "app", "path": "plugins/app/plugin.json", "api": 1, "fields": { "steps": ["enum"] } } ], "shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets", "/protobase.sw.js"] }, "native": { "@capacitor/core": "8.5.3", "@capacitor/ios": "8.5.3" }, "mobile": { "appId": "com.example.shop", "plugins": { "@capacitor/camera": "^8.0.1" }, "push": true }, "nodeModules": "node_modules", "migrations": "migrations", "realtime": { "client_events": { "channels": { "conversations": { "events": { "typing": { "schema": { "type": "object" }, "max_bytes": 256, "per_second": 2, "burst": 4 } } } } }, "presence": { "path": "/api/relay/presence", "grace_seconds": 30 } }}protobaseis the Protobase version of the copies the build used: the building CLI’s own in a bundled project, and in a locked one the@protobasepackages its lockfile installed, whichever CLI built the bundle. A host serves the bundle on the runtime of that version (see Versioning). A bundled project needs nothing installed; a locked one fails without its@protobasepackages installed.server,public,nodeModulesandmigrationsare relative to the bundle folder;spa,themeand each plugin’spathtopublic.pluginsare the bundle’s own plugins, in the order the app merges them: the extensions’, then the project’s (app). Each names itsplugin.json, the plugin API it is built for, the Protobase versions it is limited to only when itspackage.jsonnames some, and the field types it registers with the storage types each shows, which the serve runtime checks the views against at startup./api/metanames them to everyone, before any other plugin.shellis the admin apppublic/holds a copy of: its Protobase version and plugin API, and its files as URL paths. A host with a shell of its own may serve its own for those paths instead (see The UI), so the app gets that release’s fixes without a rebuild.nativeis the native code, name to version, thatshellruns on in the mobile app: the native packages@protobase/mobilepins, and@protobase/mobileitself at its native contract, such asnative-1, which Protobase raises when its own native code changes. The fingerprint of the bundle’s mobile release names them. A bundle built before it serves no mobile release.mobileis present only when the project’s config has amobilesection, so a host learns that the app has a mobile build without running the config: the section’sappId, which the statement of a signed mobile release binds, itsplugins, name to the spec it gives,{}when it gives none, andpush, whether the config hasnotifications(), with which the binaries compile native push in; the fingerprint of the mobile release names both besidesnative. A bundle built before it names noappId, and one built beforepushnone, which counts asfalse. The build checks the section asprotobase mobiledoes.themeis the project’s theme, which the app links at/protobase.theme.css. It is always there, empty when the project has none.nodeModulesis present only when the config module imports native packages. It is always thenode_modulesfolder besideserver, where Bun and Node resolve the module’s imports from, and holds plain packages: JavaScript,package.jsonfiles and native binaries for linux x64 and arm64 (glibc), which the runtime loads withdlopen. A host keeps it next to the server module and must not mount itnoexec(an add-on there then fails withfailed to map segment from shared object). Its binaries link nothing but glibc,libstdc++.so.6,libgcc_s.so.1and libraries in the bundle itself, so the run image must have those three. WithoutnodeModules, the server module is the only file the runtime reads.migrationsis present only when the project has adb/migrationsfolder: its.sqlfiles, which the runtime’smigrateapplies (see Deploy). A host never serves it.realtimeis present only when the config hasrealtime.relay, or the app has sign-in and a live resource whose conversation page hasmembers, which the platform’s switch can move to the relay: the app’s part of its entry in the apps file of Protobase Realtime, the WebSocket relay, asrelay appprints it, without the address, id or any key:client_events, when a channel resource has events, and with presencepresence, the path of the app’s presence endpoint and the reports’grace_seconds. A host that runs Realtime completes it with the app’s id, keys, origin and presence key, and the presence endpoint at the app’s address.apilists the path prefixes the server answers. A path is under a prefix when it equals it or continues it with/(/apicovers/api/metaand/api/v1:batchWrite, not/apiary). It is always/apiand the two OAuth discovery documents MCP clients read, which answer 404 without MCP: a bundle assumes the API lives under/api, with the resources at the defaultapiPath/api/v1,/api/meta, the docs, the API functions and the built-in assistant beside them and Better Auth at/api/auth. A bundle built before them sends them to the UI: rebuild it. The serve runtime refuses a config that sets anotherapiPath.- Every other path is the UI’s. A
GETorHEADfor a file inpublicgets that file; a folder gets itsindex.html. Otherwise a request whoseAcceptheader containstext/html(a navigation) getsspawith status 200, so deep links such as/orders/42load the app; anything else gets 404. Other methods get 405. - Files under an
assets/folder,public/assets/and each plugin’s, are named by their content hash and never change: serve them withCache-Control: public, max-age=31536000, immutable, and everything else,index.html, eachplugin.jsonand the theme, withno-cache. versionis the format of the manifest, not a Protobase version. A host that does not know it must refuse the bundle. Version 3 replaced version 2 when the project’s UI became a plugin beside a prebuilt app, and gainedplugins,themeandshell; version 2 replaced version 1 when the config module started to import every module the runtime supplies, and gainednodeModules.protobase serverefuses an older bundle; rebuild it withprotobase build.
The UI
Section titled “The UI”public/ holds two parts that are built apart.
- The shell,
index.html,assets/andprotobase.sw.js: the admin app, a production build of@protobase/ui’ssrc/appwith no project code in it, the same for every project on a release.@protobase/ui’s package ships it prebuilt indist/shell/and the protobase image at/opt/protobase/shell/; the build copies it. It calls the API on its own origin under/api, so the same bundle works under any hostname, and reads everything else at runtime: the resources, views, pages and roles from/api/meta, sign-in from/api/auth, the project’s UI from its plugins and its look from/protobase.theme.css, which it links after its own stylesheets, its tab icon from/protobase.favicon.svg, and its web app manifest from/api/manifest.webmanifest. - The plugins,
plugins/<name>/: the project’sprotobase.ui.tsxas the pluginapp, and each extension’s, each built asbuild-pluginbuilds one, against the CLI’s own@protobase/uiin a bundled project and the one installed in a locked project./api/metanames them, and the shell loads them as it loads any plugin. A component or field type the config declares but noprotobase.ui.tsxexports fails the build (see Components).
The modules the app shares with plugins, react, react/jsx-runtime, react-dom and @protobase/ui, are entries of their own, /assets/shared-<name>-<hash>.js, each exporting every name of its module. index.html maps the four names to them with an import map, ahead of every script, so a plugin’s imports of them run on the app’s copies.
The config module
Section titled “The config module”protobase.config.js is one ES module: the project’s config as written, protobase.config.ts or protobase.config.json, the extensions’ configs, and the code their paths find (config/, functions/, jobs/, hooks/, auth/ and the other files of Where the code is), each imported only when the app first needs it. A package the config names, such as files.images: 'sharp', is imported the same way.
-
Vite bundles the config into plain ES modules in UTF-8, which Node and Bun both load as they are.
-
With
--bun, Vite writes to a scratch folder andbun build --target bunwrites the final module. Bun’s output starts with// @bun, which tells Bun the file is already plain JavaScript: Bun neither transpiles it nor writes its transpiler cache. Bun reads such a file as Latin-1, so only Bun’s own output can carry that line: its bundler writes non-ASCII text as escapes (€as\u20AC). Raw UTF-8 with that line would load asâ¬. -
The
@protobasepackages and every package in theirdependenciesbelong to the serve runtime: their imports stayimportstatements and the runtime supplies them, so the bundle carries no copy and shares the runtime’s. It supplies these modules:Modules @protobase/config,@protobase/schema,@protobase/layout,@protobase/layout/jsx-runtime,@protobase/query,@protobase/serverthe server entry points of the @protobasepackages, and what layout files compile tokysely,kysely/helpers/postgres,pg,postgresthe database better-auth,hono,jose,zod,aip-parsers,@hono/node-server,@scalar/hono-api-referencethe main entry of each other dependency the @protobasepackages run on the serverhono/cors,hono/http-exception,hono/validatorHono middleware for API functions react,react/jsx-runtime,@react-email/renderwhat email templates render with, so a template’s component and the renderer share one React @protobase/server/pdfReact PDF’s components, which PDF documents are built from; definePdfrenders them with the runtime’s React PDF, loaded on the first document rendered@protobase/server/emailthe look of Protobase’s own mail, loaded when the bundle first imports it rather than when the runtime starts react-emailis a dependency of@protobase/serverthat the runtime does not supply: the server loads it only to send its own mail, or for@protobase/server/email, so a config that imports it inlines its own copy, like any other package.@react-pdf/rendereris a dependency of@protobase/serverthat the runtime keeps to itself: a config imports React PDF’s components from@protobase/server/pdfinstead.Importing any other
@protobasepackage or dependency of one (@protobase/ui,react-dom,better-auth/plugins,zod/v4, …) fails the build with this list, also from inside an inlined package, when the finished bundle still imports it: an inlined package may re-export a module that imports one, asreact-emaildoes withtailwindcss, as long as the project leaves that export unused. The runtime supplies them at its own versions, whichever the project installed. The list ispackages/cli/src/serve/host-module-ids.ts, and each release of@protobase/clipublishes it as@protobase/cli/host-modules.json, a JSON array of the module names, so a host reads the list of the version that serves a bundle without running it; the set of packages comes from thepackage.jsonof@protobase/cliand of every@protobasepackage it depends on. -
Packages with a native add-on stay imports too, and the bundle carries them in
node_modules/(see Native packages). Node’s built-in modules stay imports. -
Everything else (the project’s files and its other packages) is inlined. Nothing is minified.
-
Layout files (
@jsxImportSource @protobase/layout) compile to calls of@protobase/layout/jsx-runtime, for production whateverNODE_ENVsays. The build refuses one with a function, class,newvalue or hook in its JSX, naming the file, line and column (what a layout may hold). -
It exports the configs as they are, not called:
own(the project’s),extensionsandpackages. The serve runtime reads the configs again, a config function called withcommand: 'serve'and the host’s environment, merges them asprotobase devdoes and builds the app from them.
The serve runtime reads the environment when it imports the module, on the host.
Native packages
Section titled “Native packages”A package with a native add-on cannot be inlined: it loads a compiled .node file from its own folder at runtime. The build recognises one by a .node file or a binding.gyp in it, or by optional dependencies that carry the add-on per platform and name a linux one (@node-rs/argon2-linux-x64-gnu, sharp’s @img/sharp-linux-x64). For each such package the config module imports, directly or through an inlined package:
- The import stays an import, which resolves at runtime to
node_modules/<package>beside the config module. - The package and everything it needs at runtime (its dependencies and the optional ones that are installed, recursively) are copied to
node_modules/as one tree: each package at the top, a second version of one under the package that needs it. Files of a package are copied as they are, except native binaries. - Every native binary in them (ELF, Mach-O or PE, told by its headers, not its name) is copied only when it is for linux x64 or linux arm64 with glibc: the run image is Bun’s distroless image (Debian) for amd64 and arm64, and a bundle may run on either. Binaries for macOS, Windows, musl or other architectures stay behind, as do platform packages for them (by their
os,cpuandlibcfields). - Every add-on needs a
.nodebinary for both, in its package or in its platform packages. Otherwise the build fails and names each package, the platforms it misses and the ones it has. It never ships a binary built for the wrong platform. - Every binary it copies may link only glibc’s libraries, the C++ runtime (
libstdc++.so.6,libgcc_s.so.1) and libraries the bundle carries itself (sharp’s libvips); otherwise the build fails and names the binary and the library. Every add-on in common use linkslibgcc_sand, when written in C++,libstdc++. Bun’s distroless image has glibc only, so the run image adds those two (Debian’slibgcc-s1andlibstdc++6); without them an add-on fails to load (libstdc++.so.6: cannot open shared object file).
What that means for a package:
-
Prebuilt binaries for every platform inside the npm package (prebuildify and node-gyp-build:
argon2,bcrypt6,bufferutil): builds anywhere, macOS included. -
Per-platform optional packages (napi-rs, such as
@node-rs/argon2, and sharp): a package manager installs only the build machine’s, so the build fails until the linux ones are installed as well. With Bun,bun install --os='*' --cpu='*'installs every platform’s. With pnpm, inpnpm-workspace.yaml:supportedArchitectures:os: [current, linux]cpu: [current, x64, arm64]libc: [current, glibc] -
Built or downloaded on install (node-gyp from source, prebuild-install such as
better-sqlite3, node-pre-gyp): only the build machine’s binary exists, so the build fails, on a linux machine too, which has one architecture.
The bundle then runs on linux only: protobase serve of it on macOS cannot load the add-ons. Check it in a linux container of a run image with the C++ runtime, built from this Dockerfile (docker build -t protobase-run ., with --platform linux/amd64 for the other architecture):
FROM debian:trixie-slim AS libsRUN d=/usr/lib/$(uname -m)-linux-gnu && mkdir -p /out$d && cp -a $d/libstdc++.so.6* $d/libgcc_s.so.1 /out$d/FROM oven/bun:1.4.4-distrolessCOPY --from=libs /out/ /docker run --rm -p 127.0.0.1:8787:8787 -e DATABASE_URL -e PROTOBASE_URL -e PROTOBASE_SECRET \ -v "$PWD/dist:/app:ro" -v "$PWD/protobase-serve.js:/opt/protobase/protobase-serve.js:ro" \ protobase-run --no-install /opt/protobase/protobase-serve.js /app/protobase.config.jsprotobase types # writes .protobase/tsconfig.json and register.d.ts; dev, build and every command that loads the config write them tooWrites .protobase/tsconfig.json, which the project’s tsconfig.json extends ("extends": "./.protobase/tsconfig.json"). In a bundled project its paths point each @protobase package and each package the serve runtime supplies, by name and by each of its exports (@protobase/layout/jsx-runtime, kysely, zod, …), at the declarations of the CLI that builds the app, so the editor and tsc see the version that runs with nothing installed. There is no catch-all, so a package the project imports and lacks still fails as missing. React carries no types of its own, so the project keeps @types/react, as it keeps @types/node. A locked project’s installed packages type themselves, so its file holds no paths. A paths of the project’s own tsconfig.json replaces the generated one, as extends does with any option.
With a config/index.ts, it also writes .protobase/register.d.ts, which registers that module’s type with @protobase/layout, so typed layouts and <Trans> check the app’s resource names, fields and text keys, and the generated tsconfig.json includes it beside the project’s own files ("include": ["../**/*", "register.d.ts"]). A project tsconfig.json with an include of its own replaces that one, so it lists .protobase/register.d.ts there too.
.protobase/ ignores itself in git: the paths are this machine’s. Write the file again after installing another CLI; dev and build do it on every run.
protobase run <file> [args...] # e.g. "db:seed": "protobase run seed/cli.ts"Runs one of the project’s scripts, such as a seed or a migration, under Bun in a process of its own, in the current directory, with the arguments after the file, options included, passed to the script and its exit code passed back. In a bundled project the script’s imports of the @protobase packages and of every package the serve runtime supplies (kysely, pg, postgres, zod, …) get the CLI’s own copies, as a bundle gets the runtime’s, with nothing installed: a preload registers them as Bun’s virtual modules. A locked project’s script imports its installed packages. Bun never installs a missing package for it (--no-install), so a script that imports a package the project lacks fails as missing. It needs bun on PATH.
build-plugin
Section titled “build-plugin”protobase build-plugin [dir] [--out <dir>] [--name <name>] [--source-maps]Builds the plugin in dir (default: the current folder), whose entry is its protobase.ui.tsx, into --out (default: dir/dist):
dist/ plugin.json what the app reads first assets/index-<hash>.js the plugin's module, and its chunks beside it assets/styles-<hash>.css the utilities its files use- The output folder is emptied first, so it must not be the plugin’s folder or hold it.
- The module is
protobase.ui.tsxwith everything it imports bundled, except the four modules the app shares (react,react/jsx-runtime,react-dom,@protobase/ui), which stay imports by those names. Any other module of those packages, such asreact-dom/client, fails the build. React’s production build and JSX runtime are used, whateverNODE_ENVsays, and every export ofprotobase.ui.tsxis kept. - The stylesheet is Tailwind’s utilities for the classes in the plugin’s folder: no reset, no theme values. Each utility reads the theme of the app that loads it, with Tailwind’s default as the fallback (
text-smisfont-size: var(--text-sm, 0.875rem)). plugin.jsonnames the plugin (--name, else itspackage.json’sname, else its folder’s), its ownversion, the plugin API it is built for (api), what it uses (importsandextensionPoints), the Protobase versions itspackage.jsonnames inengines.protobase, if any (protobase), the module (entry) and stylesheet (css), relative to it, and the field types it registers (fields), each with the storage types it shows.apiand the extension points come from the@protobase/uiinstalled for the plugin, else for the project it extends, else the CLI’s own (see Plugins).--source-mapsends each script with a//# debugId=<uuid>comment, naming no map, and writes its source map,<script>.js.mapcarrying the samedebugId, beside it, for an error tracker to read the browser’s stack frames with.
To read its field types, the build loads the plugin’s module once in Node, with everything bundled; nothing is rendered, but code at the top level of its modules runs, so keep browser-only work (window, document) inside components and handlers. The app loads it from wherever plugin.json is served, listed in PROTOBASE_PLUGINS or the config’s plugins (see loading).
build-serve
Section titled “build-serve”protobase build-serve [--out dist/protobase-serve.js] [--bun] # or, in this repository: bun run build:serveBundles the serve runtime (@protobase/cli’s src/serve/main.ts) and all its dependencies into one file, about 3 MB. A host needs Bun and this file, nothing else. --bun has Bun’s bundler write the file, as for build, and needs bun on PATH; the protobase image is built from such a file. The file carries the Protobase version it was built from, which decides the bundles it serves.
bun --no-install protobase-serve.js [serve] <bundle> # the folder: the app and the API; the config module: the APIbun --no-install protobase-serve.js migrate <bundle> # apply the bundle's migrations to DATABASE_URLbun --no-install protobase-serve.js create-admin <bundle> <email> # [--name <name>] [--generate-password | --password-stdin]migrate runs none of the app’s code and needs only DATABASE_URL; create-admin loads the app with its settings and refuses an auth schema that is behind; without --generate-password or --password-stdin it asks for the password at a hidden prompt. Given the folder, the runtime serves the bundle’s own copy of the app. Deploy puts the three in a self-hosted image.
bun --no-install protobase-serve.js <bundle>/protobase.config.js # production, under Bun: the APIprotobase serve <bundle>/protobase.config.js # the same, with the CLI on Node or Bunprotobase serve <bundle> # the whole bundle as a host serves it, e.g. bun run --cwd tests/apps/erp serveServes the API of a bundle from protobase build and owns the process around it. Given the bundle folder, protobase serve also serves its UI by the manifest’s rules, so a bundle can be checked locally exactly as the host will serve it.
Its own shell. Given the bundle folder, protobase serve serves the manifest’s shell.paths, the root and navigations from a shell of its own when it has one: the folder PROTOBASE_SHELL names, else the prebuilt shell of the installed @protobase/ui (none when the CLI runs from this repository’s sources). Without one it serves the bundle’s copy. Its startup output says which (app the app of Protobase 0.12.3 from ...). The plugins, the theme and the API always come from the bundle.
| Variable | |
|---|---|
DATABASE_URL |
the API’s pool (Kysely over pg, 10 connections) |
PROTOBASE_DB_CONNECTIONS |
the connections that pool opens, such as the database’s limit for the app; default 10. Sign-in’s store shares them. API functions and jobs hold at most one less, so a long import leaves a connection to page and API requests; those with longQueries take theirs from one more connection, kept for them. A query waits at most 2 seconds for a free connection, then fails with 503 connections-busy (Safety); a new connection may take up to 30 seconds to open, such as while a database that scaled to zero wakes |
PORT |
default 8787 |
PROTOBASE_HOST |
the IP address the server listens on, such as 127.0.0.1 so only this computer reaches it; default every interface |
REQUEST_LOG |
true logs every request; default false |
PROTOBASE_SMTP_URL |
the SMTP server for password-reset mail, emailed sign-in and two-factor codes and the app’s own email, credential included: smtp://user:password@host:587 (STARTTLS required, ?requireTLS=false sends in plaintext, see Email) or smtps://...:465; without it they are off (Password reset, Emailed sign-in codes) |
PROTOBASE_MAIL_FROM |
the sender of that mail, a plain address such as [email protected]; set with PROTOBASE_SMTP_URL or not at all |
PROTOBASE_APP_NAME |
the app’s name, such as Property Finder: what its auth emails, its sidebar, its browser tabs and the installed app call it, and the sender’s display name of its mail, over the config’s name |
PROTOBASE_SIGN_IN_ISSUER, PROTOBASE_SIGN_IN_CLIENT_ID, PROTOBASE_SIGN_IN_CLIENT_SECRET |
an OpenID Connect provider people who have an account can sign in with; all three or none. PROTOBASE_SIGN_IN_PROVIDER, PROTOBASE_SIGN_IN_NAME, PROTOBASE_SIGN_IN_AUTHORIZATION_PARAMS, PROTOBASE_SIGN_IN_HIDDEN, PROTOBASE_SIGN_IN_BUTTON and PROTOBASE_SIGN_IN_DEVICES are optional, PROTOBASE_SIGN_IN_TOKENS=true turns on token sign-in, and PROTOBASE_SIGN_IN_<ID>_ISSUER and so on add more providers, each named by its id (Platform sign-in providers) |
PROTOBASE_OPERATOR_ISSUER, PROTOBASE_OPERATOR_CLIENT_ID, PROTOBASE_OPERATOR_CLIENT_SECRET |
the OpenID Connect provider of the operator’s staff, for staff sign-in as people of the app; all three or none. PROTOBASE_OPERATOR_NAME and PROTOBASE_OPERATOR_GROUP are optional (Operator provider) |
PROTOBASE_ORIGINS, PROTOBASE_PASSKEY_DOMAIN |
the other origins the app is served on, comma separated, and the host new passkeys are made for (Several origins) |
PROTOBASE_CORS_ORIGINS |
other websites whose browser code may call the API, * or comma separated http and https origins (CORS) |
PROTOBASE_PREVIOUS_SECRETS |
the app’s secrets before PROTOBASE_SECRET, newest first, comma separated, which still decrypt what they encrypted, unless the config sets previousSecrets |
PROTOBASE_TRUSTED_ORIGINS |
extra origins that may call the auth endpoints, comma separated, unless the config sets auth.trustedOrigins |
PROTOBASE_PUBLISHABLE_KEY, PROTOBASE_SECRET_KEY |
the app’s API keys, unless the config sets apiKeys |
PROTOBASE_PLUGINS, PROTOBASE_PLUGINS_BEFORE_SIGN_IN |
plugins a hosting platform adds to the app, their plugin.json URLs comma separated; the second also load before sign-in |
PROTOBASE_FORMS_SECRET |
the secret public forms sign their bot checks with, over the app’s secret |
PROTOBASE_VAPID_PUBLIC_KEY, PROTOBASE_VAPID_PRIVATE_KEY, PROTOBASE_VAPID_SUBJECT |
the key pair and contact of Web Push, from notifications vapid-keys |
PROTOBASE_ASSISTANT_URL, PROTOBASE_ASSISTANT_API_KEY, PROTOBASE_ASSISTANT_MODEL, PROTOBASE_ASSISTANT_BASE_URL |
the assistant: a backend elsewhere, or the built-in one on OpenRouter or another OpenAI-compatible endpoint; without them there is none |
PROTOBASE_ASSISTANT_CHATS |
the folder the built-in assistant keeps its conversations in; default .protobase/chats |
PROTOBASE_FIRST_ADMIN_URL |
the hosting platform’s page where the app’s first user is added, such as its console’s; while the app has no users, the sign-in page links there in place of the protobase users create command (the first admin) |
PROTOBASE_RUNS_ON_NOTE |
true ends the sign-in page on the Runs on Protobase note, for a hosting platform; default false, and any value but true or false stops startup |
PROTOBASE_RUNTIME_URL |
the endpoint behind the top bar’s runtime update button, such as a hosting platform’s; without it there is no button |
PROTOBASE_SENTRY_DSN |
the DSN of a Sentry-compatible error tracker the app’s server and admin app send their errors to, after the config’s errorReporting (Error reporting); without it nothing is sent |
PROTOBASE_REALTIME_URL, PROTOBASE_REALTIME_APP, PROTOBASE_REALTIME_API_KEY, PROTOBASE_REALTIME_TICKET_KEY, PROTOBASE_REALTIME_PRESENCE_KEY |
the address, the app’s id, its API and ticket keys and its presence key of Protobase Realtime, the WebSocket relay, each where the config’s realtime.relay leaves it out; without realtime.relay or PROTOBASE_REALTIME_ENABLED the relay stays off |
PROTOBASE_REALTIME_ENABLED |
true when the platform moves the app to Realtime, with the channels of realtime.relay or else of its live resources whose conversation page has members; true for an app with neither stops the server. Unset or empty is false; any other value stops the server |
PROTOBASE_MAP_STYLE_URL |
the URL of the MapLibre style the record page’s maps are drawn with, after the config’s maps; without it there are no maps |
PROTOBASE_SOURCES |
other Protobase APIs whose resources the app draws as its own, a JSON list of { "url", "label", "resources", "roles"? } after the config’s remoteResources (Remote resources) |
PROTOBASE_FILES_<NAME>, PROTOBASE_FILES_RETENTION, PROTOBASE_FILES_SECRET |
file providers and their settings, over files in the config; a bucket’s credentials in PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID and _SECRET_ACCESS_KEY |
PROTOBASE_FILES_CLEANUP_MINUTES |
minutes between runs of the scheduled file deletes, default 60; 0 leaves them to protobase files cleanup or the platform |
PROTOBASE_ENCRYPTION_KEY, PROTOBASE_ENCRYPTION_PREVIOUS_KEYS |
the key encrypted fields are sealed with, 32 random bytes in base64 (openssl rand -base64 32), and the comma separated keys they were sealed with before, which still open them |
PROTOBASE_JOBS |
false runs none of the app’s jobs in this process, which still enqueues them; default true |
PROTOBASE_STARTUP_CHECKS |
false skips the startup reads of the auth, changes, computed columns, webhooks and jobs schemas, which make a start slower; default true. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
PROTOBASE_SHELL |
protobase serve <bundle> only: a shell folder, such as the /opt/protobase/shell of a protobase image or @protobase/ui’s dist/shell, to serve the bundle’s app from (see its own shell) |
PROTOBASE_TRUSTED_PROXIES |
the proxies in front of the server, addresses or CIDR ranges, comma separated: a request from one of them names its client in X-Forwarded-For; without it the client is the connection’s address (Client addresses) |
PROTOBASE_MOBILE_SIGNING_KEY |
an RSA private key of at least 2048 bits, PEM, its newlines real or written \n, that signs every file of the mobile release in X-Signature and its statement, for an app whose updater checks signatures with the matching public key; another kind of key, or a shorter one, stops startup |
PROTOBASE_JOBS_DRAIN_TOKEN |
the operator’s bearer token for POST /api/jobs/drain, which runs the due jobs of a host that lets the app sleep; without it there is no such endpoint |
The app’s address and secret are PROTOBASE_URL and PROTOBASE_SECRET unless its config sets url and secret (see App options); its other settings are the project’s own variables, read by its config, which the runtime reads again at start with the host’s environment. protobase serve also loads the nearest .env, like dev; the runtime takes the environment as it is.
- Routes:
createAdmin(/api/v1,/api/meta,/api/functions/*,/api/auth/*, …) andGET /health, which answers{"status":"ok"}without a token and without touching the database. The runtime never serves the UI;protobase serve <bundle>servespublic/for every path outside the manifest’sapiand/.well-known/webauthn, after/health, withX-Frame-Options: DENYandContent-Security-Policy: frame-ancestors 'none', so no other site frames its pages. - Plugins: the runtime reads the manifest’s
plugins:/api/metanames them, and a view that shows a field with one of their field types that does not show the field’s storage type stops startup, naming the view, the field and what the field type shows. - Manifest: a config module needs its
protobase.bundle.jsonbeside it. The runtime checks no version: the host picks the runtime from the manifest’sprotobase(see Versioning). - Startup: a config module that
protobase builddid not write, a config with anapiPathother than/api/v1, or one with sign-in on and no secret or URL, stops startup with a one-line error and exit code 1, as does a missingDATABASE_URL, an auth store that has not applied every migration of this version, or has a newer one (seeauth migration), a resource over a table of the auth store, a resource whose events or history lack their triggers or have out-of-date ones, or a missing history or comments table, a rollup or formula field whose column or trigger is missing or out of date, a jobs schema that is missing or behind for a config with jobs (seemigration), an AI field or action without a model key, encrypted fields without a key, or another resource over their column, or a taken port;PROTOBASE_STARTUP_CHECKS=falseskips the checks of those schemas and the key.protobase serve listening on port <port>means it is ready. - Jobs: with jobs in the config it runs them beside the API, unless
PROTOBASE_JOBS=false, and withPROTOBASE_JOBS_DRAIN_TOKENit answersPOST /api/jobs/drainfor the operator. - Shutdown: the first SIGTERM or SIGINT stops accepting connections, answers the requests held open waiting at once (a runner’s claim gets no job), closes open WebSockets with 1001 (dropping any still open after 5 seconds), and waits for open requests, answering each with
Connection: closeso a client that polls on a kept-alive connection asks no more of this process; a request still open after 30 seconds has its connection dropped. It then gives running jobs 30 seconds to finish, drains the poolservecreated and exits with 0. - Host modules: under Bun, the runtime registers the modules it supplies as virtual modules, so the bundle needs no
node_modulesfor them.protobase serveandprotobase workerunder Bun do the same with the CLI’s own copies, whatever the project installed, so a bundle runs on the copies of the CLI that runs it. On Node both resolve them from theprotobase serveandprotobase workeron Node cannot give a bundle the CLI’s own host modules because a module hook for Node is not implemented.node_modulesnext to the bundle, so there keep the bundle inside the project, whose installed versions it then runs on. Native packages load from the bundle’s ownnode_modules/under both. - Read-only hosts: nothing is written: no install (
--no-install), and for a bundle built with--bunno transpiling and so no transpiler cache. A bundle withnode_modules/needs its folder mounted withoutnoexec, since its add-ons are mapped as executable code.
Mobile releases
Section titled “Mobile releases”With a mobile section, the server serves the mobile app a newer copy of its files, for its live updater, so the app gets UI changes without a store release. The release is what the server serves the web, composed at startup: every file of public/, with the server’s own shell where protobase serve uses it, and index.html naming the API origin, the app’s url (https, or plain http to localhost, 127.0.0.1 or [::1]). There is none when the server serves the API alone, has no such url, or the bundle names no native, and with PROTOBASE_MOBILE_SIGNING_KEY none for a bundle that names no build time (one built before Protobase recorded it: build it again). Where protobase serve serves its own shell, the release’s fingerprint names the native of that shell’s protobase.shell.json, and there is none when it names none.
GET /api/mobile/release?fingerprint=<native fingerprint>&shell_version=<x.y.z>answers{ "bundleId", "url", "required" }: the release’s id, a hash of its files, and its absolute base URL, bothnullwhen the release does not run on the asking binary, whose native fingerprint must equal the release’s, or when the update is required, since the binary refuses a release of another shell version.requiredis true when the shell the app runs no longer works with the server’s API: below 1.0 another minor, from 1.0 another major. A missing fingerprint or a shell version that is no x.y.z version gets 400.GET /api/mobile/releases/<bundleId>?href=<file>serves the release’s file<file>, such asassets/index-abc123.js, and withhref=capawesome-live-update-manifest.jsonits manifest, a JSON array of{ "href", "checksum", "sizeInBytes" }. Each comes with its sha256 in hex inX-Checksumand, withPROTOBASE_MOBILE_SIGNING_KEY, its signature inX-Signature. Any other file, or another release’s id, gets 404.- Signed, a release also serves
href=protobase-release.json, its statement:{ "payload", "signature" }, the payload the hex of the JSON{ "manifest", "order", "appId", "fingerprint", "shellVersion" }and the signature the hex of its SHA256withRSA over the lineprotobase-mobile-releaseand the payload. It binds the manifest’s sha256 to the release’s order, when the bundle was built and then when the server’s own shell it serves was built (0 with the bundle’s copy), to the app id and native fingerprint of the binaries it runs on, and to the server’s Protobase version. Its id is then a hash of the statement and the public key, so the same files built again get another id. A file of the app may not be named like the statement or start with that line. - The app, on Android and iOS alike, downloads a release itself and takes it only when its statement is signed with the key the binary pins, names the release’s id, this app, this binary and a server its shell works with, and its order is not below the highest it downloaded; then every file must hash to what the manifest lists, under a path inside the release, before any file is written. It follows no redirect and reads no file past the size its manifest lists. It runs a downloaded release only above the running one’s order and holding nothing but the files its manifest lists. It never takes a release at or below the order of its own files, which
protobase mobilerecords in the binary as the server would order the same bundle with its copy of the shell, so a reinstalled app is not taken below them, and a release built before the binary is not taken.A phone cannot take a rollback of the bundle or of the server’s shell before a later build, because ordering releases by an explicit release number is not implemented. An app with no download recorded, such as after a reinstall, cannot refuse a genuine signed release older than the latest but newer than its own files, because a signed answer naming the latest release is not implemented.
The live updater
Section titled “The live updater”An Android or iOS app built with mobile.publicKey updates itself from the server it calls, and never shows that it does. Launch waits on nothing: the app starts on the release it set next earlier, or its own files. The shell asks GET /api/mobile/release in the background each time the app comes back to the foreground and, while someone is signed in, once the app has drawn, every 15 minutes while it is in view and when the server’s Protobase version changes under an open page. It downloads a release it does not run, only the files that changed, and runs it at the next cold start. The session stays in the device’s cookie store, so the user stays signed in across the switch.
-
The splash screen stays up from launch until the app draws past its loading screens, the sign-in check,
/metaand the plugins, so someone signed in sees the page from the start cache as it goes. It covers each reload into a release the same way. -
Right after someone signs in on the app, before it opens, the app takes the server’s release and reloads into it, on the same page. Past 20 seconds it opens on the files it runs, and the download goes on for a later start or return.
-
Coming back to the foreground after 5 minutes or more away, the app reloads into a release it downloaded, then returns to the page and scroll position it showed. It does not while a guard holds unsaved changes on the page, or when it was away for less. The app shows no prompt that it was updated: a reload would only start the files it runs again, so it checks for the server’s release instead. A push tapped while the app reloads opens its page once the release has drawn.
-
Once the shell has drawn, it tells the updater the release started. A release that does not within 30 seconds goes back to the app’s own files at once and is never taken again.
-
No answer, any status but 200, a body that is not the answer, or an answer naming no release changes nothing: the app keeps the files it runs, and never goes back to its own files because of the answer, which is not signed.
-
A required update offers no release, so the app goes on with the files it runs.
A required update across a Protobase minor below 1.0, or a major, cannot reach a phone by live update because taking a release of another shell version than the binary’s is not implemented, so such a fix, a security fix included, reaches it only through a store release. -
The binary pins the public key: a new key needs a new store release, and a server whose
PROTOBASE_MOBILE_SIGNING_KEYis not its private half serves releases the app refuses.
A host that serves bundles without running their config, such as a router in front of many apps or a static host, serves the same release from the files it already serves with @protobase/server/mobile-release, which loads none of the rest of the server: protobase serve composes its own release with the same exports.
nativeFingerprint(native, plugins, { push }): the release’s fingerprint, from the manifest’snative(or that of the shell the host serves),mobile.pluginsandmobile.push,falsewhen the manifest names none. A host that leavespushout matches no binary of an app withnotifications(). It is a contract across versions: a binary one Protobase release built is matched by a host that runs another.releaseOrder({ builtAt, shell }): the order a release signs, from the manifest’s build time and that of the server’s own shell the host serves in its place,[builtAt, 0]with the bundle’s copy;undefinedwhen either names no build time.withApiOrigin(html, origin): thespapage naming the API origin, the app’surl.composeRelease(files, signing?): the release of{ href, content }files, every file the host serves the web with the page above in place ofspa, with its id and, withsigning,{ key, binding: { order, appId, fingerprint, shellVersion } },appIdthe manifest’smobile.appId, the signed checksums and statement.readSigningKey(env): the signing key inPROTOBASE_MOBILE_SIGNING_KEYof the env object given, the app’s own, never the process’s.mobileReleaseApp({ release, serverVersion }): a Hono app answering the two routes above for{ ...release, fingerprint, origin }.
worker
Section titled “worker”protobase worker <bundle> # a bundle from `protobase build`: its folder or its protobase.config.jsRuns the bundle’s jobs, and the delivery of its events, and nothing else, until SIGTERM or SIGINT, which let running jobs finish for 30 seconds as serve does. It checks the bundle’s version and the jobs schema at start like serve, reads the .env nearest the current directory and needs DATABASE_URL. Run it beside a serve with PROTOBASE_JOBS=false, from the same bundle. It refuses a bundle with nothing to run: no jobs, no resource with events, history, comments or an AI field, and no time rollup, whose jobs are Protobase’s own. Like serve, it reports a crash to the app’s error tracker. protobase worker running <n> jobs means it is ready.
files cleanup
Section titled “files cleanup”protobase files cleanup # the project in the current directoryprotobase files cleanup <bundle> # a bundle from `protobase build`: its folder or its protobase.config.jsRuns the scheduled file deletes that are due: replaced and cleared files past their retention, and uploads nobody saved. A file a row references again is kept. It prints each file it deleted or kept. It reads the .env nearest the current directory and needs DATABASE_URL. protobase serve runs the same every hour; this is for cron, or a host that turns that off.
encryption status
Section titled “encryption status”protobase encryption status # the project in the current directoryprotobase encryption status <bundle> # a bundle from `protobase build`: its folder or its protobase.config.jsReads every encrypted field’s column and prints its values per key id, the current one marked, its plaintext values, and each value that does not decrypt by record key, with why (not-encrypted, malformed, unknown-key, failed-authentication) and never the value. It also prints the history rows and undispatched changes that still hold a field’s old values, encrypted values in fields that are not encrypted, and foreign keys on update cascade that change a record’s key. It writes nothing, so it shows what apply would do. It exits with 1 when anything is plaintext, under a previous key, unreadable, misplaced or left in history, so a script can gate on it. It takes the keys from the environment and the .env nearest the current directory, like serve, and needs DATABASE_URL.
encryption apply
Section titled “encryption apply”protobase encryption apply [bundle]protobase encryption apply --rebind people --from-table persons # after a table renameprotobase encryption apply --rebind people.iban --from-column bank_iban # after a column renameEncrypts every plaintext value of the encrypted fields with the current key, encrypts values under a previous key again with it, and removes the fields’ old values from the history and the changes not yet dispatched. Values that do not decrypt are listed and left as they are; it exits with 1 when any remain. Its writes are captured by no event, history or webhook, and a value a write changes while it runs is left to that write. It refuses to run when a column holds values under none of its keys, such as with another key than the app’s.
--rebind <resource>[.<field>] with --from-table <table> (as .table() wrote it) or --from-column <column> also takes values sealed where the field was before a rename, and seals them where it is now; running it again rebinds nothing more. It refuses a former place another resource still encrypts.
Run it at update time, after the migrations and before the new version serves, and again once an old version that wrote plaintext has stopped. It works over one database connection.
notifications vapid-keys
Section titled “notifications vapid-keys”protobase notifications vapid-keysPrints a fresh key pair for Web Push as PROTOBASE_VAPID_PUBLIC_KEY and PROTOBASE_VAPID_PRIVATE_KEY lines to paste into the environment or .env, and says to set PROTOBASE_VAPID_SUBJECT too. It reads no project, writes no file and makes no request.
protobase users create <email> [--name <name>] [--role <role>] [--password-stdin | --generate-password | --no-password] [--github-id <id>] [--organization <organization> [--org-role <role>] [--app-roles <a,b>]]protobase users listprotobase users rolesprotobase users set-role <email> <role>protobase users disable <email> # and: enable <email>protobase users delete <email> [--yes]Run inside a project with sign-in on (its config’s auth, on unless false, or unless the config leaves auth out and sets authenticate.jwksUrl). Like organizations, token and auth migration, it reads the .env nearest the project and needs DATABASE_URL. There is no web setup page, and open sign-up, when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever --role says; later users get --role, or the project’s default role (auth: { roles, defaultRole } in its config). protobase users roles lists the roles of the project; anything else is refused with that list. set-role also takes comma separated roles (sales,accountant). --github-id links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app’s own provider or the platform’s, finds them whatever address GitHub reports; an id that signs in another user already is refused. createUser(auth, { ..., accounts: [{ providerId, accountId }] }) does the same from code.
The password is typed at a hidden prompt with confirmation, read from stdin with --password-stdin (for scripts, e.g. pass show erp | protobase users create [email protected] --password-stdin), or generated with --generate-password and printed once; it must be 12 to 128 characters, the length the app requires of every new password. --no-password makes an account without one, which signs in by emailed code, passkey or a sign-in provider, as with an app whose sign-in policy turns passwords off. A password is never accepted as an argument, since it would end up in shell history. users list prints email, role and creation date (and disabled for banned users), never credentials.
delete asks you to type the email back (or pass --yes), and needs a terminal otherwise. delete, set-role and disable refuse to touch the last admin, so the project cannot lock itself out. disable bans the user and revokes their sessions; tokens already issued stop working on their next request, and protobase token refuses disabled users. With MCP on, it also disconnects their MCP clients. enable lifts the ban; the clients have to be allowed again. protobase dev prints the command that creates the first admin at startup while the user table is empty (see dev).
With organizations, --role is the user’s global role (none by default) and --organization adds the new user to an organization, by its slug or id, with --org-role (owner, admin, or member, the default) and --app-roles there.
organizations
Section titled “organizations”protobase organizations listprotobase organizations create <name> --owner <email> [--slug <slug>] [--id <id>] [--members all]protobase organizations add-member <organization> <email> [--org-role <role>] [--app-roles <a,b>]protobase organizations set-roles <organization> <email> [--org-role <role>] [--app-roles <a,b>]protobase organizations remove-member <organization> <email>protobase organizations add-app-role <role> --to ownersFor a project with organizations; <organization> is a slug or an id. The host acts as a superuser, so it may give any role. create makes --owner the owner with every app role; --id keeps an existing tenant value, and --members all adds every other user, superusers as owners and everyone else as a member with their global roles moved onto the membership, for an app that ran as one organization. remove-member and set-roles refuse to leave an organization without an owner. add-app-role gives a role the project added later to every owner.
migrate
Section titled “migrate”protobase migrate [connection string | --env VAR] [--plan]Applies the project’s db/migrations/*.sql that the database has not applied yet, in file name order, as the runtime’s migrate applies a bundle’s: in one transaction behind the same lock, recorded in the same migrations.applied (see Deploy), so a database either one migrated is current for the other. It prints each file it applies, or that the database is up to date; a project without db/migrations applies nothing and says so. It runs none of the project’s code, so a project with only protobase.config.ts, no package.json and nothing installed, migrates as well. The URL comes as for scaffold, and is needed only when there are migrations. A project that still has a db/migrate.ts recording in public.schema_migrations first copies in the presets’ current db/migrate.ts and drop.ts, so the two keep one record. --plan is a dry run: it prints each file not applied yet under its name, with its SQL, from a read-only transaction, and applies and records nothing.
migration
Section titled “migration”protobase migration [--dir db/migrations] [--extend <dir>]protobase migration --custom <name> [--record-config]protobase migration checkprotobase migration dropprotobase migration upWrites what the config and this version of Protobase need beyond the project’s protobase.snapshot.json as the project’s next migration in --dir: one numbered file each run, named after what it holds, such as 004_auth.sql or 005_changes_webhooks.sql, after the folder’s highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: -- protobase:id, a random id of its own, then the version that wrote it, each sign-in module’s last step, and the hash of the snapshot’s model once it is applied. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project’s other migrations.
The snapshot describes the schema the project’s migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with modelHash, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its format and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization; and physical, every schema, table, column and index name the store has. The sign-in store’s part of the file comes from the snapshot alone, without a database: the steps after each module’s last one, those a newer Protobase ships included, each version followed by its row in auth_migrations, which the server’s startup check reads. With DATABASE_URL set, the checks of those steps run first against the database’s rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in auth.tables, is refused with what changed, since Protobase does not write renames: write it by hand with --custom and --record-config. protobase migration cannot write the sign-in store of a project with auth migrations from before protobase.snapshot.json because protobase migration baseline, which reads the database once to start the snapshot, is not implemented.
The rest of the file is what the other features the config enables still need of the database, compared with it, each under its own comment and named in the file name as in brackets: the jobs schema when the config has jobs, webhooks, workflows, notifications or mailFeedback, or a resource has events, history, comments or an AI field or is a time rollup (jobs), the table of the bounces and complaints of mailFeedback (mail_feedback), the capture of events and the history table (changes), the columns of rollup and formula fields, the triggers that keep the rollups, and the tables, indexes and refresh functions of time rollups (computed), the role the assistant’s read-only queries run as, when it finds the built-in assistant’s key (query), the comments table (comments), the webhook subscriptions of webhooks (webhooks), the workflows, versions, runs and steps of workflows (workflows), the devices and history tables of notifications (notifications), the table of who unsubscribed from bulk mail of unsubscribe (unsubscribes), the realtime_relay schema of realtime: { processes: 'many' } (realtime_relay), the channels schema of realtime: { sqlSends: true } (channel_sends), the trigger of realtime.relay that ends a deleted session’s sockets and realtime.members with the triggers that keep it from channel records that list their members, also for an app with sign-in and a live resource whose conversation page has members (relay), and, with userTables, the schemas of user tables (user_tables) and the delete of the definitions of tables that resources in code own now (owned_definitions). Those are compared only with DATABASE_URL set, against the database with the project’s migrations applied, and the command says so without it. protobase migration cannot write the jobs, change capture, rollup and other feature schemas from the snapshot because recording their models in it is not implemented.--extend as dev merges them, and the .env nearest the current directory.
--custom <name>writes an empty numbered file,NNN_<name>.sql, with Protobase’s lines and-- protobase:custom, for statements you write by hand, and makes the snapshot end at it. It counts as not additive; once it only adds, put-- protobase:additiveamong its-- protobase:lines andchecklints it with the lint rules Protobase’s own steps pass, such as no dropped table or column, no new required column and no unique constraint without a check of the rows. With--record-config, the snapshot takes the sign-in store’s names as the config has them now, each module at the step it was: the file is where you make the store match, such as a rename.check, for CI, writes nothing and exits 1 with a line for each problem: a config or Protobase version that needs steps the migrations lack, a name the config changed, two files that share a number when Protobase wrote one of them, a snapshot that does not end at the newest file Protobase wrote or whose model does not match itsmodelHash, and a hand-written file marked additive that is not.dropdeletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file’s lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch’s file, and after a file that recorded a changed config, whose snapshot before it only version control has.uprewrites the snapshot in this version’s format. Every other command refuses a snapshot of an older format, and one of a newer format, which only a newer Protobase reads.
When two branches each write a migration, both rewrite the snapshot, so merging the second reports a conflict in protobase.snapshot.json, and the commands refuse until it is resolved. On the second branch, delete its own new file, take the other branch’s snapshot, and run protobase migration again: it writes the second branch’s changes as one file after the other’s.
bun run protobase migration # writes db/migrations/NNN_auth.sql and protobase.snapshot.json for what the config enablesbun run protobase migration check # in CI: exits 1 when the migrations lack a change of the configbun run db:migrate # applies thembuckets rebuild
Section titled “buckets rebuild”protobase buckets rebuild <resource> # every bucketprotobase buckets rebuild <resource> --from 2026-07-01 # from the bucket of that day's first hour onRecounts a time rollup’s buckets from the one --from falls in, or all of them without it, in one statement through the rollup’s refresh function, such as after importing records older than its late. --from takes a date or a date and time, such as 2026-07-01T10:00, in UTC unless it names a zone (2026-07-01T10:00+02:00); anything else stops with an error naming it. It writes only the rollup’s table, and refuses a resource that is not a time rollup. It reads the .env nearest the current directory and needs DATABASE_URL.
relay app
Section titled “relay app”protobase relay appPrints the app’s entry for the apps file of Realtime, as JSON: its id, api_keys and ticket_keys from realtime.relay, or else PROTOBASE_REALTIME_APP, PROTOBASE_REALTIME_API_KEY and PROTOBASE_REALTIME_TICKET_KEY, and in origins the origin of the app’s url (or PROTOBASE_URL); in client_events each channel resource’s client events, those of its conversation pages with members when it declares no channels, with typing on those whose conversation page types; with presence, presence with the app’s presence endpoint at that url, the presence key (or PROTOBASE_REALTIME_PRESENCE_KEY) and a grace_seconds of 30. Its client_events and presence path and grace are the bundle manifest’s realtime. Add the relay’s limits and options to it there. It reads protobase.config.ts with command: 'tool' and the .env nearest the current directory.
auth migration
Section titled “auth migration”protobase auth migration [--dir db/migrations] [--name auth]Run inside a project, against its database with the project’s migrations applied. It reads the versions the store applied from its auth_migrations table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in --dir: 009_auth.sql after 008_..., with the store’s schema, user table, columns and id type as the config’s auth names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project’s other migrations. It starts with Protobase’s lines and starts the project’s protobase.snapshot.json, or moves it on, with the store at every step, so migration goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it. For a store made before 0.48, without auth_migrations, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See migrations.
import supabase
Section titled “import supabase”protobase import supabase [<connection> | --source-env <variable>] [--env DATABASE_URL] [--dir db/migrations] [--config config] [--storage-url <url>] [--storage-key-env SUPABASE_SERVICE_ROLE_KEY] [--yes]Turns a Supabase project’s database into the project in the current directory, in two runs with the project’s migrations between them. It needs PostgreSQL’s pg_dump and psql on PATH, of the Supabase database’s major version or newer, and reads the .env nearest the current directory for the project’s database (--env).
-
The first run takes the Supabase database’s connection string, for its
postgresrole (the session pooler’s or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase’sauthandstorageschemas and itssupabase_adminrole, and whileauth.usershas single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email, so the import cannot carry them over. It then says how many share their address with another user and how many have one of their own, and printsselect id, email from auth.users where is_sso_userto list them rather than their addresses. Deleting a user in Supabase deletes or breaks the app’s rows that reference it, so what to do about these users is the developer’s decision, made in Supabase before importing again. It notes the Supabase CLI’ssupabase/config.toml,supabase/migrations/andsupabase/functions/when the checkout has them. It convertssupabase/functionsinto the project’sfunctions/(see functions moved from Supabase):Deno.serve(handler)and std’sserve(handler)becomeexport default defineFunction({ supabase: true }, { fetch: handler }), an existing default export is wrapped the same way, so each function also answers at/api/sb/functions/v1/<name>,npm:,jsr:and esm.sh imports become bare imports of packages it adds topackage.json,Deno.env.get(name)becomesprocess.env[name],EdgeRuntime.waitUntilbecomeswaitUntilof@protobase/server, a function withverify_jwt = falseinconfig.tomlbecomes public ({ public: true, supabase: true }), and_sharedand the like are converted beside them. It stops before anything else whenfunctions/already has one of their names. It dumpsauth,storageand every schema the app made, schema and data apart, as of one snapshot, leaving out the platform’s own migration tables, and writes the schemas as the project’s next migration,NNN_supabase_schema.sql. It asks the project’s database which of the app’s extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase’s Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, thesupabase_functions.http_requestfunction their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges fordashboard_user,supabase_*,authenticatorandpostgres, statements about thepublicschema, Realtime’s publication, pgsodium’s security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable’s insert-blocking trigger. It then writesNNN_supabase_users.sql, the nullable columns Better Auth needs onauth.users(name,email_verified,image,app_role,banned,ban_reason,ban_expires) and GoTrue’s'authenticated'as the default ofroleandaud. It writesNNN_supabase_realtime.sql, which makesrealtime.messages,realtime.topic(), and Supabase’srealtime.send()andrealtime.broadcast_changes(), so the app’s triggers and SQL keep broadcasting from the database, with the source’s row security policies onrealtime.messages, so its private channels keep their access; a policy that names only Supabase’s own roles is left out as a comment. It points the app atauth.users: theauthofprotobase.config.tsgetstables: { user: { name: 'users', columns: { role: 'app_role' } } },users: { metadata: 'raw_user_meta_data', guardedSchemas: ['auth'] },passwordHashes: ['bcrypt']andgenerateUserId: 'uuid', or the config gets anauthof them when it has none (see an existing users table). It removes the migrationsprotobase auth migrationorprotobase migrationwrote for Protobase’s own user table, sinceauth.usersreplaces it, and stops before writing anything when the project has noprotobase.config.ts, or one whoseauthis not an object it can see, or when the project’s database has a schema the dump creates already, such as theauthschema those migrations made. The project’s database needs the rolesanon,authenticatedandservice_rolethat the dump’s grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes tosupabase-import/, which it adds to.gitignore, since it holds every row and the users’ password hashes. Where the project’s database can create Vault, pgmq and pg_cron,supabase-import/replay.sqlholds what a dump cannot carry: Vault’s secrets with their values, read decrypted since only Supabase’s key opens their ciphertext, pgmq’s queues with their messages, since pgmq owns their tables, and pg_cron’s jobs, which live in its own schema. -
Apply the migration with the project’s other migrations, such as
bun run db:migrate. -
The second run, without a connection string, loads the data in one transaction, with the app’s triggers off so a sign-up trigger on
auth.usersdoes not run again for users who already have their rows, and fails the transaction unless every table holds the source’s number of rows. In the same transaction it makes Vault’s secrets and pgmq’s queues again throughvault.create_secret,pgmq.createandpgmq.send, each message with its headers and the time it becomes visible. Where the project’s database has pg_cron, as Supabase’s Postgres image does when it serves that database, it schedules pg_cron’s jobs again there withcron.schedule, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a recurring job of its own injobs/, of the same name, schedule andcron.timezone, that runs its SQL as the app’s database role, tried once each time as pg_cron did, and declares it in thejobsofprotobase.config.ts(or writes one); they run oncemigrationhas added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net’snet.http_*,cronor Vault, an inactive one and a schedule recurring jobs do not take, such as30 secondsor$, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runsscaffoldon the imported tables of the app’s schemas (notauthorstorage), giving the tables of thesupabase_realtimepublication.live()so/api/sb/realtime/v1keeps sending theirpostgres_changesoncemigrationhas written their capture triggers, writes Better Auth’s other tables next toauth.usersasauth migrationdoes (NNN_auth.sql), thenNNN_supabase_accounts.sql, and writessupabase-import/report.md: the rows loaded, the API keys/api/sbneeds and thecreateClientchange to the app’s/api/sband its publishable key, the imported tables’ size against the Starter plan’s 500 MB, each sign-in provider’s identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase’s ciphertext, whose values to export decrypted in Supabase before declaring them.encrypted()and runningencryption apply, the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (deno.land/ximports, Deno’s file, KV and WebSocket APIs,Supabase.ai), and the indexesdoctorfinds missing.NNN_supabase_accounts.sqlfills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name fromraw_user_meta_data’sfull_nameorname, the picture from itsavatar_urlorpicture,email_verifiedfromemail_confirmed_at, and a ban frombanned_until, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, acredentialaccount (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth’s name for it (azureismicrosoft, keyed on theoidclaim;linkedin_oidcislinkedin,slack_oidcisslack,xistwitter), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities and sessions do not carry over.The import cannot carry over MFA factors because that is not implemented. The import cannot carry over passkeys because that is not implemented. -
Apply the migrations again. Supabase’s users then sign in with their own passwords, and with a social provider once it is in the
socialProvidersof the config’sauth; new users get a UUID inauth.users, so the app’s triggers there run for them. -
Storage’s files: with
--storage-url https://<ref>.supabase.coand the project’s secret key in the variable--storage-key-envnames,SUPABASE_SERVICE_ROLE_KEYby default, the second run, or any run after it, copies the bytes of every object instorage.objectsfrom the Supabase project’s Storage API into the app’s Storage file provider, where/api/sb/storage/v1serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket’s size and stops when what is left to copy and what the provider holds exceed the provider’smax_bytes, unless--yes. An object that fails does not stop the rest; the run then fails, listing them insupabase-import/storage.md, and a rerun copies only what the provider does not hold yet. The key goes only in the requests’ headers, never in a file. Plainhttp://is accepted only for a local Supabase onlocalhost,127.0.0.1or[::1], such assupabase start’shttp://127.0.0.1:54321, since the key bypasses every Storage policy; a download Supabase answers with a redirect is not followed, so the key goes to no other host, and that object fails.
An agent with the supabase-move skill of skill install finishes what the report leaves: it rewrites each item, checking the project’s database for the extensions an item needs, and runs doctor and the typecheck until both pass, leaving the values of Vault’s secrets for you to enter. It keeps supabase/functions, the Deno originals the app no longer runs, out of the typecheck through the exclude of tsconfig.json, and removes the folder only when you say so.
Remove supabase-import/ to import again.
mobile
Section titled “mobile”protobase mobile run <ios|android> [--api <url>] [--target <id>] [--team <id>] [--live] [--port <port>] [--extend <dir>]protobase mobile open <ios|android> [--api <url>] [--extend <dir>]protobase mobile build <ios|android> --app-version <x.y.z> --build-number <n> [--api <url>] [--out mobile-release] [--extend <dir>] [--team <id> [--certificate <name> --profile <name>]]protobase mobile keysBuilds the project in the current directory as an iOS or Android app with Capacitor, from the mobile section of its protobase.config.ts; without one it stops and says what to add. --extend <dir> (repeatable) merges an extension’s protobase.config.ts and protobase.ui.tsx before the project’s, as build does. See A mobile app.
- It installs
@protobase/mobile, of the CLI’s version, which pins Capacitor and its plugins, with the section’spluginsinto.protobase/mobile/with npm, when that changed, and on every run for a package from a local folder, given asfile:or a path such as../my-plugin, which npm copies. When such a folder’s dependencies are not the versions installed, it removes the workspace’snode_modulesandpackage-lock.jsonso npm resolves them again, and stops when a pin is still not met, as when two packages pin one dependency at different versions. It builds the app’s files asbuilddoes and keeps onlypublic/, itsindex.htmlnaming the API origin; writescapacitor.config.json, compiling in only the section’s plugins; and generates the platform’s native project again, replacing the last one. --apiis the server the app calls, the app’surlby default: an http or https origin, plain http only tolocalhost,127.0.0.1and, on iOS,[::1], or on Android10.0.2.2. An Android app callinglocalhostgets the port forwarded.runruns the app on--target, or asks for one. On iOS,--teamwrites the Apple team id into the generated project and builds it once with xcodebuild allowed to create the development profile and register the device,--targetor the one connected device, before Capacitor runs it there. With--liveit opensprotobase devonlocalhost:--portinstead of its own files, by default on the portdevkeeps for the project, and stops when it keeps none yet.openopens the native project in Xcode or Android Studio.buildmakes a signed release, an.aab(Android) or.ipa(iOS), and copies it to--out, which ignores itself in git when the command creates it, as<appId>-<version>-<build number>. Android signs through Gradle with the keystore, alias and passwords inPROTOBASE_ANDROID_KEYSTORE,PROTOBASE_ANDROID_KEY_ALIAS,PROTOBASE_ANDROID_KEYSTORE_PASSWORDandPROTOBASE_ANDROID_KEY_PASSWORD; iOS archives and exports with xcodebuild for--team, letting Xcode create certificates and profiles with the account in its settings, or with the App Store Connect API key inPROTOBASE_IOS_API_KEY_PATH,PROTOBASE_IOS_API_KEY_IDandPROTOBASE_IOS_API_KEY_ISSUER;--certificatewith--profilesigns manually through Capacitor’s build.- A release calls an https server that is not this machine, and
--app-version(one to three numbers) and--build-number(1 to 2100000000) are required. - npm and Capacitor get the CLI’s environment without any variable named in the current directory’s
.env*files, nor the fourPROTOBASE_ANDROID_*signing variables, which only Gradle gets, and withCI=true, which keeps Capacitor’s telemetry off. The project’s config, its extensions’ configs and the web build run inside the CLI with noPROTOBASE_ANDROID_*variable left in its environment, even one the project’s.envsets. - It prints the workspace, the API origin and the native fingerprint, which the app also sends in its user agent as
ProtobaseNative/<fingerprint>: a hash of the native packages@protobase/mobilepins, at their versions, its own native contract, and the section’splugins, at the versions they give. A mobile release runs only on a binary of its own fingerprint. A Protobase release that pins the same native packages and keeps the same native contract keeps it; raise a plugin’s version when the app’s files start using a newer native feature of it, which changes it. - The app’s files carry the live updater’s manifest of them, so an update downloads only the files that changed.
- With
mobile.publicKey, the Android and iOS app get the live updater, unless--liveis given, the app’s files name no build time, or the API is neither https nor http tolocalhost,127.0.0.1or[::1], which only iOS’s--apiaccepts; it prints a note why when it leaves it out. An Android--apiof10.0.2.2, the emulator’s host, gets no live updater. On Android, http tolocalhostor127.0.0.1works only in a debuggable app, asrunbuilds it: a release build’s live updater does not load with one. keysprints a fresh RSA key pair:PROTOBASE_MOBILE_SIGNING_KEY=<key>, on one line with its newlines written\n, for the server’s environment, a secret never to commit, and the public key, PEM, formobile.publicKey. It reads no project and writes no file.
protobase token <email> [--ttl 15m] [--organization <slug|id>]Prints a bearer token (JWT, signed with the project’s Better Auth keys, same claims as a browser token) for an existing user. The lifetime is 30s, 15m, 24h, … up to 24 hours, default 15 minutes. With organizations, --organization names the one the token works in; without it, the token works where a new session of the user would start. Only the token goes to stdout and errors go to stderr, so it composes in scripts:
curl -H "Authorization: Bearer $(protobase token me@x)" http://localhost:23456/api/v1/orders?page_size=1protobase skill install [name]Copies the agent skills of this CLI’s version into the current project, or only the one name names. protobase, the protobase agent skill, goes to .agents/skills/protobase/ (read by Codex, Cursor, OpenCode and Amp) and .claude/skills/protobase/ (read by Claude Code): a short SKILL.md with the everyday workflow and the checks before calling a change done, and the guides and reference of this version as files it points to. protobase-cloud goes to .agents/skills/protobase-cloud/ and .claude/skills/protobase-cloud/: how an app hosted on protobase-cloud deploys from GitHub, how to check that a change went live, and why a deploy failed. supabase-move goes beside them: it has an agent work through supabase-import/report.md after import supabase, item by item, until doctor and the app’s typecheck pass. Each replaces an earlier copy, and refuses to touch a folder of its name that holds another skill. Commit the folders, and run the command again after upgrading the @protobase packages. The skills also ship in node_modules/@protobase/cli/skills, where the skills CLI’s experimental_sync finds it.
ERP example
Section titled “ERP example”bun run db:up && bun run --cwd tests/apps/erp db:migrate && bun run --cwd tests/apps/erp db:seed --scale smallbun run --cwd tests/apps/erp protobase scaffold postgres://protobase:protobase@localhost:55432/protobase \ --yes --ui --exclude public.seed_infobun run --cwd tests/apps/erp protobase doctor postgres://protobase:protobase@localhost:55432/protobaseThe ERP keeps Better Auth’s users, sessions and signing keys in the auth schema of the same database; scaffold leaves that store out on its own, so they are never exposed through the admin API. --exclude leaves out the seed’s own bookkeeping table.
The integration test (packages/cli/tests/scaffold/scaffold.integration.test.ts) scaffolds into a temp folder and is skipped when the database is unreachable.