powersync
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePowerSync Skills
PowerSync实践指南
Best practices and expertise for building applications with PowerSync.
使用PowerSync构建应用的最佳实践与专业方案。
Architecture
架构
mermaid
flowchart LR
subgraph BACKEND["Your Backend"]
direction TB
DB["Backend Database (Postgres | MongoDB | MySQL | Supabase | …)"]
API["Backend API (Your server / cloud functions)"]
API -- "Applies writes" --> DB
end
subgraph PS_SERVICE["PowerSync Service"]
direction TB
SYNC["Partial Sync (sync rules filter data per user)"]
end
subgraph APP["Your App"]
direction TB
SDK["PowerSync SDK"]
SQLITE["In-app SQLite (local replica — reads are instant)"]
QUEUE["Upload Queue (offline write buffer)"]
UI["UI"]
SDK --- SQLITE
SDK --- QUEUE
SQLITE <--> UI
QUEUE <--> UI
end
DB -- "Replicates changes (CDC / logical replication)" --> PS_SERVICE
PS_SERVICE -- "Streams changes (real-time sync)" --> SDK
QUEUE -- "Uploads writes (when connectivity resumes)" --> APIKey rule: client writes never go through PowerSync — they go directly from the app's upload queue to your backend API. PowerSync only handles the read/sync path.
mermaid
flowchart LR
subgraph BACKEND["Your Backend"]
direction TB
DB["Backend Database (Postgres | MongoDB | MySQL | Supabase | …)"]
API["Backend API (Your server / cloud functions)"]
API -- "Applies writes" --> DB
end
subgraph PS_SERVICE["PowerSync Service"]
direction TB
SYNC["Partial Sync (sync rules filter data per user)"]
end
subgraph APP["Your App"]
direction TB
SDK["PowerSync SDK"]
SQLITE["In-app SQLite (local replica — reads are instant)"]
QUEUE["Upload Queue (offline write buffer)"]
UI["UI"]
SDK --- SQLITE
SDK --- QUEUE
SQLITE <--> UI
QUEUE <--> UI
end
DB -- "Replicates changes (CDC / logical replication)" --> PS_SERVICE
PS_SERVICE -- "Streams changes (real-time sync)" --> SDK
QUEUE -- "Uploads writes (when connectivity resumes)" --> API核心规则:客户端写入操作绝不经过PowerSync——它们直接从应用的上传队列发送至你的后端API。PowerSync仅负责读取/同步路径。
Getting Started — PowerSync Service Setup
入门指南——PowerSync服务搭建
When setting up the PowerSync Service, ask the user two questions if the answers aren't clear from context:
- Cloud or Self-hosted? — PowerSync Cloud (managed) or self-hosted (run your own Docker instance)?
- Dashboard or CLI? — For Cloud: set up via the PowerSync Dashboard UI, or via the PowerSync CLI? For Self-hosted: manual Docker setup, or use the CLI's Docker integration?
Then follow the matching path below. For all paths, also load and .
references/powersync-service.mdreferences/sync-config.md在搭建PowerSync服务时,如果上下文未明确相关信息,请向用户询问两个问题:
- 云端部署还是自行托管?——PowerSync Cloud(托管版)还是自行托管(运行自己的Docker实例)?
- 使用控制台还是CLI?——对于云端版:通过PowerSync Dashboard UI配置,还是使用PowerSync CLI?对于自行托管版:手动Docker搭建,还是使用CLI的Docker集成?
然后按照以下对应路径操作。所有路径都需要同时查阅和。
references/powersync-service.mdreferences/sync-config.mdPath 1: Cloud — Dashboard Setup
路径1:云端版——控制台搭建
No CLI needed. The user does everything through the PowerSync Dashboard.
Guide the user through these steps:
- Sign up and create a project — the user needs a PowerSync account at https://dashboard.powersync.com. Once signed in, they must create a project before they can create an instance.
- Create a PowerSync instance — inside the project, create a new instance.
- Connect the source database — in the instance settings, add the database connection. The user needs to provide:
- Database type (Postgres, MongoDB, MySQL, etc.)
- Connection URI or host/port/database/username/password
- The database must have replication enabled — see → Source Database Setup for the SQL commands the user needs to run.
references/powersync-service.md
- Configure sync rules — in the instance's Sync Config editor, write Sync Streams that define what data each user receives. Must use . See
config: edition: 3for the format.references/sync-config.md - Enable client authentication — in the instance's "Client Auth" section, configure JWT verification (JWKS URI, Supabase Auth, etc.). For development, enable "Development Tokens" in this section.
- Get the instance URL — copy the instance URL from the dashboard. The app's needs this as the PowerSync endpoint.
fetchCredentials()
IMPORTANT: All steps must be completed. If any are missing, the app will be stuck on "Syncing..." with no data.
无需使用CLI,用户可通过PowerSync Dashboard完成所有操作。
引导用户完成以下步骤:
- 注册并创建项目——用户需要在https://dashboard.powersync.com注册PowerSync账号。登录后,必须先创建项目才能创建实例。
- 创建PowerSync实例——在项目内创建新的实例。
- 连接源数据库——在实例设置中添加数据库连接。用户需要提供:
- 数据库类型(Postgres、MongoDB、MySQL等)
- 连接URI或主机/端口/数据库名/用户名/密码
- 数据库必须启用复制功能——查阅→ 源数据库设置,获取用户需要执行的SQL命令。
references/powersync-service.md
- 配置同步规则——在实例的同步配置编辑器中,编写同步流(Sync Streams)来定义每个用户可获取的数据。配置必须以开头。具体格式请查阅
config: edition: 3。references/sync-config.md - 启用客户端认证——在实例的“客户端认证”板块,配置JWT验证(JWKS URI、Supabase Auth等)。开发环境下,可在此板块启用“开发令牌”。
- 获取实例URL——从控制台复制实例URL。应用的方法需要将此作为PowerSync的端点地址。
fetchCredentials()
**重要提示:**所有步骤必须全部完成。若有任何步骤遗漏,应用将一直停留在“同步中...”状态,无法获取数据。
Path 2: Cloud — CLI Setup
路径2:云端版——CLI搭建
Load for full CLI reference.
references/powersync-cli.mdWhat to ask the user before starting:
- Do they have a PowerSync account? If not, direct them to https://dashboard.powersync.com to sign up.
- Have they created a project on the dashboard? If not, they need to create one first at https://dashboard.powersync.com (a project is required before creating an instance).
- Do they have an existing instance, or should we create a new one?
查阅获取完整的CLI参考文档。
references/powersync-cli.md开始前需向用户确认的信息:
- 他们是否已有PowerSync账号?如果没有,引导他们前往https://dashboard.powersync.com注册。
- 他们是否已在控制台创建项目?如果没有,需要先在https://dashboard.powersync.com创建项目(创建实例前必须先有项目)。
- 他们是否已有现有实例,还是需要创建新实例?
New Cloud Instance
新建云端实例
-
Install and authenticate:bash
npm install -g powersync powersync loginopens a browser for the user to create/paste a personal access token (PAT). If they don't have one: https://dashboard.powersync.com/account/access-tokenspowersync login -
Scaffold config files:bash
powersync init cloudThis createsandpowersync/service.yamlwith template values.powersync/sync-config.yaml -
Read the scaffolded files, then prompt the user for their database connection details and edit the files:
- — fill in
powersync/service.yamlwith database type, host, port, database name, username, and password. For Cloud, usereplication.connectionsfor credentials. Seepassword: secret: !env PS_DATABASE_PASSWORDfor the correct YAML structure.references/powersync-service.md - — must start with
powersync/sync-config.yaml, then defineconfig: edition: 3. Write Sync Streams based on the app's tables. Seestreams:.references/sync-config.md
-
Ask the user for their project ID, then create the instance and deploy:bash
powersync link cloud --create --project-id=<project-id> # Add --org-id=<org-id> only if their token has access to multiple orgs powersync validate powersync deployThe user can find their project ID on the PowerSync Dashboard under their project settings or by running.powersync fetch instances -
Set up the source database — the user must configure their database for replication. See→ Source Database Setup for the SQL commands. For Supabase, logical replication is already enabled but the user still needs to create the publication via the Supabase SQL Editor.
references/powersync-service.md -
Generate a dev token for testing:bash
powersync generate token --subject=user-test-1Use this token in the app'sduring development.fetchCredentials() -
Verify:— confirm the instance is connected and replicating.
powersync status
-
安装并认证:bash
npm install -g powersync powersync login会打开浏览器,让用户创建/粘贴个人访问令牌(PAT)。如果没有令牌,可前往https://dashboard.powersync.com/account/access-tokens获取。powersync login -
生成配置文件模板:bash
powersync init cloud此命令会创建和powersync/service.yaml两个文件,并填充模板值。powersync/sync-config.yaml -
查看生成的配置文件,然后提示用户提供数据库连接信息并编辑文件:
- ——在
powersync/service.yaml中填写数据库类型、主机、端口、数据库名、用户名和密码。对于云端版,凭证请使用replication.connections格式。正确的YAML结构请查阅password: secret: !env PS_DATABASE_PASSWORD。references/powersync-service.md - ——必须以
powersync/sync-config.yaml开头,然后定义config: edition: 3。根据应用的表结构编写同步流。具体请查阅streams:。references/sync-config.md
-
向用户索要项目ID,然后创建实例并部署:bash
powersync link cloud --create --project-id=<project-id> # 如果令牌有权限访问多个组织,需添加--org-id=<org-id> powersync validate powersync deploy用户可在PowerSync控制台的项目设置中找到项目ID,或通过运行命令获取。powersync fetch instances -
配置源数据库——用户必须为数据库配置复制功能。具体SQL命令请查阅→ 源数据库设置。对于Supabase,逻辑复制已默认启用,但用户仍需通过Supabase SQL编辑器创建发布规则。
references/powersync-service.md -
生成开发令牌用于测试:bash
powersync generate token --subject=user-test-1开发期间,可在应用的中使用此令牌。fetchCredentials() -
**验证:**运行——确认实例已连接并正在复制数据。
powersync status
Existing Cloud Instance
现有云端实例
Ask the user for their project ID and instance ID, then pull the config:
bash
powersync login
powersync pull instance --project-id=<project-id> --instance-id=<instance-id>向用户索要项目ID和实例ID,然后拉取配置:
bash
powersync login
powersync pull instance --project-id=<project-id> --instance-id=<instance-id>Add --org-id=<org-id> only if token has multiple orgs
如果令牌有权限访问多个组织,需添加--org-id=<org-id>
The user can find these IDs on the PowerSync Dashboard or by running `powersync fetch instances`.
**WARNING:** `powersync pull instance` silently overwrites local `service.yaml` and `sync-config.yaml`. Do not run it if there are uncommitted local changes to those files.
After pulling, edit files as needed, then:
```bash
powersync validate
powersync deploy用户可在PowerSync控制台或通过运行`powersync fetch instances`命令获取这些ID。
**警告:**`powersync pull instance`会静默覆盖本地的`service.yaml`和`sync-config.yaml`文件。如果这些文件有未提交的本地修改,请勿运行此命令。
拉取配置后,按需编辑文件,然后运行:
```bash
powersync validate
powersync deployPath 3: Self-Hosted — Manual Docker Setup
路径3:自行托管——手动Docker搭建
No CLI needed. The user runs Docker directly with the PowerSync Service image.
-
Set up the source database — see→ Source Database Setup.
references/powersync-service.md -
Create the config file — create awith the correct structure. See
config.yaml→ Complete service.yaml Example. Key sections:references/powersync-service.md- — the database connection (must be nested here, not at root level)
replication.connections - — bucket storage database (MongoDB or Postgres, separate from source DB)
storage - — JWT verification settings
client_auth - — API key for management access
api.tokens
-
Run the Docker container:bash
docker run \ -p 8080:80 \ -e POWERSYNC_CONFIG_B64="$(base64 -i ./config.yaml)" \ --network my-local-dev-network \ --name my-powersync journeyapps/powersync-service:latest -
Create the sync config — write sync rules (see) either inline in
references/sync-config.mdor via the built-in dashboard atconfig.yaml.http://localhost:8080
For more details on manual Docker setup, see .
references/powersync-service.md无需使用CLI,用户直接通过Docker运行PowerSync Service镜像。
-
配置源数据库——查阅→ 源数据库设置。
references/powersync-service.md -
创建配置文件——创建文件并按正确结构编写。具体请查阅
config.yaml→ 完整service.yaml示例。核心板块:references/powersync-service.md- ——数据库连接(必须嵌套在此处,而非根层级)
replication.connections - ——存储桶数据库(MongoDB或Postgres,需与源数据库分离)
storage - ——JWT验证设置
client_auth - ——用于管理访问的API密钥
api.tokens
-
运行Docker容器:bash
docker run \ -p 8080:80 \ -e POWERSYNC_CONFIG_B64="$(base64 -i ./config.yaml)" \ --network my-local-dev-network \ --name my-powersync journeyapps/powersync-service:latest -
创建同步配置——编写同步规则(查阅),可直接内联在
references/sync-config.md中,或通过内置控制台config.yaml配置。http://localhost:8080
手动Docker搭建的更多细节请查阅。
references/powersync-service.mdPath 4: Self-Hosted — CLI with Docker
路径4:自行托管——CLI结合Docker
The CLI manages the Docker Compose stack for local development. Load for full CLI reference.
references/powersync-cli.md-
Install the CLI and scaffold:bash
npm install -g powersync powersync init self-hosted -
Read the scaffolded, then prompt the user for connection details. If using
powersync/service.yaml, the user needs to provide their source database URI. Otherwise the CLI provisions a local Postgres in Docker. See--database externalfor the YAML structure (references/powersync-service.md,replication.connections,storage,client_auth).api.tokens -
Configure and start the Docker stack:bash
powersync docker configure # Use --database external if connecting to an existing database # Use --storage external if using an existing storage database powersync docker start -
Verify and generate tokens:bash
powersync status powersync generate schema --output=ts --output-path=./schema.ts powersync generate token --subject=user-test-1
For Docker stop/reset/cleanup commands, see → Docker section.
references/powersync-cli.mdCLI用于管理Docker Compose栈,适用于本地开发。完整CLI参考请查阅。
references/powersync-cli.md-
安装CLI并生成模板:bash
npm install -g powersync powersync init self-hosted -
查看生成的文件,然后提示用户提供连接信息。如果使用
powersync/service.yaml,用户需要提供源数据库的URI。否则CLI会在Docker中自动创建本地Postgres数据库。YAML结构(--database external、replication.connections、storage、client_auth)请查阅api.tokens。references/powersync-service.md -
配置并启动Docker栈:bash
powersync docker configure # 如果连接现有数据库,使用--database external # 如果使用现有存储数据库,使用--storage external powersync docker start -
验证并生成令牌:bash
powersync status powersync generate schema --output=ts --output-path=./schema.ts powersync generate token --subject=user-test-1
Docker的停止/重置/清理命令请查阅 → Docker板块。
references/powersync-cli.mdWhat to Load for Your Task
不同任务需查阅的文件
| Task | Load these files |
|---|---|
| New project setup | |
| Handling file uploads / attachments | |
| Setting up PowerSync with Supabase (database, auth, fetchCredentials) | |
| Debugging sync / connection issues | |
| Writing or migrating sync config | |
| Configuring the service / self-hosting | |
| Using the PowerSync CLI | |
| Understanding the overall architecture | This file is sufficient; see |
| 任务 | 需查阅的文件 |
|---|---|
| 新项目搭建 | |
| 处理文件上传/附件 | |
| 结合Supabase配置PowerSync(数据库、认证、fetchCredentials) | |
| 调试同步/连接问题 | |
| 编写或迁移同步配置 | |
| 配置服务/自行托管 | |
| 使用PowerSync CLI | |
| 理解整体架构 | 本文件已足够;如需深入了解请查阅 |
SDK Reference Files
SDK参考文件
JavaScript / TypeScript
JavaScript / TypeScript
Always load as the foundation for any JS/TS project, then load the applicable framework file alongside it.
references/sdks/powersync-js.md| Framework | Load when… | File |
|---|---|---|
| React / Next.js | React web app or Next.js | |
| React Native / Expo | React Native, Expo, or Expo Go | |
| Vue / Nuxt | Vue or Nuxt | |
| Node.js / Electron | Node.js CLI/server or Electron | |
| TanStack | TanStack Query or TanStack DB (any framework) | |
所有JS/TS项目都需以为基础,再结合适用的框架文件。
references/sdks/powersync-js.md| 框架 | 适用场景 | 文件 |
|---|---|---|
| React / Next.js | React网页应用或Next.js | |
| React Native / Expo | React Native、Expo或Expo Go | |
| Vue / Nuxt | Vue或Nuxt | |
| Node.js / Electron | Node.js CLI/服务器或Electron | |
| TanStack | TanStack Query或TanStack DB(任意框架) | |
Other SDKs
其他SDK
| Platform | Load when… | File |
|---|---|---|
| Dart / Flutter | Dart / Flutter (includes Drift ORM + Flutter Web) | |
| .NET | .NET (MAUI, WPF, Console) | |
| Kotlin | Kotlin (Android, JVM, iOS, macOS, watchOS, tvOS) | |
| Swift | Swift / iOS / macOS (includes GRDB ORM) | |
| 平台 | 适用场景 | 文件 |
|---|---|---|
| Dart / Flutter | Dart / Flutter(包含Drift ORM + Flutter Web) | |
| .NET | .NET(MAUI、WPF、控制台应用) | |
| Kotlin | Kotlin(Android、JVM、iOS、macOS、watchOS、tvOS) | |
| Swift | Swift / iOS / macOS(包含GRDB ORM) | |
Key Rules to Apply Without Being Asked
无需询问即可遵循的核心规则
- Use the CLI for instance operations — when deploying config, generating schemas, generating dev tokens, checking status, or managing Cloud/self-hosted instances, use CLI commands. See
powersyncfor usage.references/powersync-cli.md - Sync Streams over Sync Rules — new projects must use Sync Streams (edition 3 config). Sync Rules are legacy; only use them when an existing project already has them.
- column — never define
idin a PowerSync table schema; it is created automatically asid.TEXT PRIMARY KEY - No boolean/date column types — use (0/1) for booleans and
column.integer(ISO string) for dates.column.text - is fire-and-forget — do not
connect()expecting data to be ready. Useawait connect()if you need to wait.waitForFirstSync() - is mandatory — if it is never called, the upload queue stalls permanently.
transaction.complete() - on logout —
disconnectAndClear()keeps local data;disconnect()wipes it. Always usedisconnectAndClear()when switching users (this will however cause the client to do a full re-sync when connecting again).disconnectAndClear() - Backend must return 2xx for validation errors — a 4xx response from blocks the upload queue permanently.
uploadData
- 使用CLI执行实例操作——部署配置、生成Schema、生成开发令牌、查看状态或管理云端/自行托管实例时,使用CLI命令。具体用法请查阅
powersync。references/powersync-cli.md - 优先使用同步流(Sync Streams)而非同步规则(Sync Rules)——新项目必须使用同步流(版本3配置)。同步规则为旧版功能;仅当现有项目已使用时才继续使用。
- 列——绝不要在PowerSync表Schema中定义
id;它会自动创建为id类型。TEXT PRIMARY KEY - 禁止使用布尔/日期列类型——布尔值使用(0/1)表示,日期使用
column.integer(ISO字符串)表示。column.text - 是“触发即遗忘”——不要通过
connect()等待数据准备就绪。如果需要等待,请使用await connect()。waitForFirstSync() - 必须调用——如果从未调用此方法,上传队列会永久停滞。
transaction.complete() - 登出时使用——
disconnectAndClear()会保留本地数据;disconnect()会清除本地数据。切换用户时请始终使用disconnectAndClear()(但这会导致客户端再次连接时执行全量重新同步)。disconnectAndClear() - 后端对验证错误需返回2xx状态码——返回4xx响应会导致上传队列永久阻塞。
uploadData