powersync

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PowerSync 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)" --> API
Key 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:
  1. Cloud or Self-hosted? — PowerSync Cloud (managed) or self-hosted (run your own Docker instance)?
  2. 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
references/powersync-service.md
and
references/sync-config.md
.
在搭建PowerSync服务时,如果上下文未明确相关信息,请向用户询问两个问题:
  1. 云端部署还是自行托管?——PowerSync Cloud(托管版)还是自行托管(运行自己的Docker实例)?
  2. 使用控制台还是CLI?——对于云端版:通过PowerSync Dashboard UI配置,还是使用PowerSync CLI?对于自行托管版:手动Docker搭建,还是使用CLI的Docker集成?
然后按照以下对应路径操作。所有路径都需要同时查阅
references/powersync-service.md
references/sync-config.md

Path 1: Cloud — Dashboard Setup

路径1:云端版——控制台搭建

No CLI needed. The user does everything through the PowerSync Dashboard.
Guide the user through these steps:
  1. 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.
  2. Create a PowerSync instance — inside the project, create a new instance.
  3. 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
      references/powersync-service.md
      → Source Database Setup for the SQL commands the user needs to run.
  4. Configure sync rules — in the instance's Sync Config editor, write Sync Streams that define what data each user receives. Must use
    config: edition: 3
    . See
    references/sync-config.md
    for the format.
  5. 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.
  6. Get the instance URL — copy the instance URL from the dashboard. The app's
    fetchCredentials()
    needs this as the PowerSync endpoint.
IMPORTANT: All steps must be completed. If any are missing, the app will be stuck on "Syncing..." with no data.
无需使用CLI,用户可通过PowerSync Dashboard完成所有操作。
引导用户完成以下步骤:
  1. 注册并创建项目——用户需要在https://dashboard.powersync.com注册PowerSync账号。登录后,必须先创建项目才能创建实例。
  2. 创建PowerSync实例——在项目内创建新的实例。
  3. 连接源数据库——在实例设置中添加数据库连接。用户需要提供:
    • 数据库类型(Postgres、MongoDB、MySQL等)
    • 连接URI或主机/端口/数据库名/用户名/密码
    • 数据库必须启用复制功能——查阅
      references/powersync-service.md
      → 源数据库设置,获取用户需要执行的SQL命令。
  4. 配置同步规则——在实例的同步配置编辑器中,编写同步流(Sync Streams)来定义每个用户可获取的数据。配置必须以
    config: edition: 3
    开头。具体格式请查阅
    references/sync-config.md
  5. 启用客户端认证——在实例的“客户端认证”板块,配置JWT验证(JWKS URI、Supabase Auth等)。开发环境下,可在此板块启用“开发令牌”。
  6. 获取实例URL——从控制台复制实例URL。应用的
    fetchCredentials()
    方法需要将此作为PowerSync的端点地址。
**重要提示:**所有步骤必须全部完成。若有任何步骤遗漏,应用将一直停留在“同步中...”状态,无法获取数据。

Path 2: Cloud — CLI Setup

路径2:云端版——CLI搭建

Load
references/powersync-cli.md
for full CLI reference.
What 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?
查阅
references/powersync-cli.md
获取完整的CLI参考文档。
开始前需向用户确认的信息:

New Cloud Instance

新建云端实例

  1. Install and authenticate:
    bash
    npm install -g powersync
    powersync login
    powersync login
    opens 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-tokens
  2. Scaffold config files:
    bash
    powersync init cloud
    This creates
    powersync/service.yaml
    and
    powersync/sync-config.yaml
    with template values.
  3. Read the scaffolded files, then prompt the user for their database connection details and edit the files:
    • powersync/service.yaml
      — fill in
      replication.connections
      with database type, host, port, database name, username, and password. For Cloud, use
      password: secret: !env PS_DATABASE_PASSWORD
      for credentials. See
      references/powersync-service.md
      for the correct YAML structure.
    • powersync/sync-config.yaml
      — must start with
      config: edition: 3
      , then define
      streams:
      . Write Sync Streams based on the app's tables. See
      references/sync-config.md
      .
  4. 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 deploy
    The user can find their project ID on the PowerSync Dashboard under their project settings or by running
    powersync fetch instances
    .
  5. Set up the source database — the user must configure their database for replication. See
    references/powersync-service.md
    → 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.
  6. Generate a dev token for testing:
    bash
    powersync generate token --subject=user-test-1
    Use this token in the app's
    fetchCredentials()
    during development.
  7. Verify:
    powersync status
    — confirm the instance is connected and replicating.
  1. 安装并认证:
    bash
    npm install -g powersync
    powersync login
    powersync login
    会打开浏览器,让用户创建/粘贴个人访问令牌(PAT)。如果没有令牌,可前往https://dashboard.powersync.com/account/access-tokens获取。
  2. 生成配置文件模板:
    bash
    powersync init cloud
    此命令会创建
    powersync/service.yaml
    powersync/sync-config.yaml
    两个文件,并填充模板值。
  3. 查看生成的配置文件,然后提示用户提供数据库连接信息并编辑文件:
    • powersync/service.yaml
      ——在
      replication.connections
      中填写数据库类型、主机、端口、数据库名、用户名和密码。对于云端版,凭证请使用
      password: secret: !env PS_DATABASE_PASSWORD
      格式。正确的YAML结构请查阅
      references/powersync-service.md
    • powersync/sync-config.yaml
      ——必须以
      config: edition: 3
      开头,然后定义
      streams:
      。根据应用的表结构编写同步流。具体请查阅
      references/sync-config.md
  4. 向用户索要项目ID,然后创建实例并部署:
    bash
    powersync link cloud --create --project-id=<project-id>
    # 如果令牌有权限访问多个组织,需添加--org-id=<org-id>
    powersync validate
    powersync deploy
    用户可在PowerSync控制台的项目设置中找到项目ID,或通过运行
    powersync fetch instances
    命令获取。
  5. 配置源数据库——用户必须为数据库配置复制功能。具体SQL命令请查阅
    references/powersync-service.md
    → 源数据库设置。对于Supabase,逻辑复制已默认启用,但用户仍需通过Supabase SQL编辑器创建发布规则。
  6. 生成开发令牌用于测试:
    bash
    powersync generate token --subject=user-test-1
    开发期间,可在应用的
    fetchCredentials()
    中使用此令牌。
  7. **验证:**运行
    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 deploy

Path 3: Self-Hosted — Manual Docker Setup

路径3:自行托管——手动Docker搭建

No CLI needed. The user runs Docker directly with the PowerSync Service image.
  1. Set up the source database — see
    references/powersync-service.md
    → Source Database Setup.
  2. Create the config file — create a
    config.yaml
    with the correct structure. See
    references/powersync-service.md
    → Complete service.yaml Example. Key sections:
    • replication.connections
      — the database connection (must be nested here, not at root level)
    • storage
      — bucket storage database (MongoDB or Postgres, separate from source DB)
    • client_auth
      — JWT verification settings
    • api.tokens
      — API key for management access
  3. 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
  4. Create the sync config — write sync rules (see
    references/sync-config.md
    ) either inline in
    config.yaml
    or via the built-in dashboard at
    http://localhost:8080
    .
For more details on manual Docker setup, see
references/powersync-service.md
.
无需使用CLI,用户直接通过Docker运行PowerSync Service镜像。
  1. 配置源数据库——查阅
    references/powersync-service.md
    → 源数据库设置。
  2. 创建配置文件——创建
    config.yaml
    文件并按正确结构编写。具体请查阅
    references/powersync-service.md
    → 完整service.yaml示例。核心板块:
    • replication.connections
      ——数据库连接(必须嵌套在此处,而非根层级)
    • storage
      ——存储桶数据库(MongoDB或Postgres,需与源数据库分离)
    • client_auth
      ——JWT验证设置
    • api.tokens
      ——用于管理访问的API密钥
  3. 运行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
  4. 创建同步配置——编写同步规则(查阅
    references/sync-config.md
    ),可直接内联在
    config.yaml
    中,或通过内置控制台
    http://localhost:8080
    配置。
手动Docker搭建的更多细节请查阅
references/powersync-service.md

Path 4: Self-Hosted — CLI with Docker

路径4:自行托管——CLI结合Docker

The CLI manages the Docker Compose stack for local development. Load
references/powersync-cli.md
for full CLI reference.
  1. Install the CLI and scaffold:
    bash
    npm install -g powersync
    powersync init self-hosted
  2. Read the scaffolded
    powersync/service.yaml
    , then prompt the user for connection details. If using
    --database external
    , the user needs to provide their source database URI. Otherwise the CLI provisions a local Postgres in Docker. See
    references/powersync-service.md
    for the YAML structure (
    replication.connections
    ,
    storage
    ,
    client_auth
    ,
    api.tokens
    ).
  3. 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
  4. 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
references/powersync-cli.md
→ Docker section.
CLI用于管理Docker Compose栈,适用于本地开发。完整CLI参考请查阅
references/powersync-cli.md
  1. 安装CLI并生成模板:
    bash
    npm install -g powersync
    powersync init self-hosted
  2. 查看生成的
    powersync/service.yaml
    文件
    ,然后提示用户提供连接信息。如果使用
    --database external
    ,用户需要提供源数据库的URI。否则CLI会在Docker中自动创建本地Postgres数据库。YAML结构(
    replication.connections
    storage
    client_auth
    api.tokens
    )请查阅
    references/powersync-service.md
  3. 配置并启动Docker栈:
    bash
    powersync docker configure
    # 如果连接现有数据库,使用--database external
    # 如果使用现有存储数据库,使用--storage external
    powersync docker start
  4. 验证并生成令牌:
    bash
    powersync status
    powersync generate schema --output=ts --output-path=./schema.ts
    powersync generate token --subject=user-test-1
Docker的停止/重置/清理命令请查阅
references/powersync-cli.md
→ Docker板块。

What to Load for Your Task

不同任务需查阅的文件

TaskLoad these files
New project setup
references/powersync-cli.md
+
references/powersync-service.md
+
references/sync-config.md
+ SDK files for your platform (see below)
Handling file uploads / attachments
references/attachments.md
Setting up PowerSync with Supabase (database, auth, fetchCredentials)
references/supabase-auth.md
Debugging sync / connection issues
references/powersync-debug.md
Writing or migrating sync config
references/sync-config.md
Configuring the service / self-hosting
references/powersync-service.md
+
references/powersync-cli.md
Using the PowerSync CLI
references/powersync-cli.md
+
references/sync-config.md
Understanding the overall architectureThis file is sufficient; see
references/powersync-overview.md
for deep links
任务需查阅的文件
新项目搭建
references/powersync-cli.md
+
references/powersync-service.md
+
references/sync-config.md
+ 对应平台的SDK文件(见下文)
处理文件上传/附件
references/attachments.md
结合Supabase配置PowerSync(数据库、认证、fetchCredentials)
references/supabase-auth.md
调试同步/连接问题
references/powersync-debug.md
编写或迁移同步配置
references/sync-config.md
配置服务/自行托管
references/powersync-service.md
+
references/powersync-cli.md
使用PowerSync CLI
references/powersync-cli.md
+
references/sync-config.md
理解整体架构本文件已足够;如需深入了解请查阅
references/powersync-overview.md

SDK Reference Files

SDK参考文件

JavaScript / TypeScript

JavaScript / TypeScript

Always load
references/sdks/powersync-js.md
as the foundation for any JS/TS project, then load the applicable framework file alongside it.
FrameworkLoad when…File
React / Next.jsReact web app or Next.js
references/sdks/powersync-js-react.md
React Native / ExpoReact Native, Expo, or Expo Go
references/sdks/powersync-js-react-native.md
Vue / NuxtVue or Nuxt
references/sdks/powersync-js-vue.md
Node.js / ElectronNode.js CLI/server or Electron
references/sdks/powersync-js-node.md
TanStackTanStack Query or TanStack DB (any framework)
references/sdks/powersync-js-tanstack.md
所有JS/TS项目都需以
references/sdks/powersync-js.md
为基础,再结合适用的框架文件。
框架适用场景文件
React / Next.jsReact网页应用或Next.js
references/sdks/powersync-js-react.md
React Native / ExpoReact Native、Expo或Expo Go
references/sdks/powersync-js-react-native.md
Vue / NuxtVue或Nuxt
references/sdks/powersync-js-vue.md
Node.js / ElectronNode.js CLI/服务器或Electron
references/sdks/powersync-js-node.md
TanStackTanStack Query或TanStack DB(任意框架)
references/sdks/powersync-js-tanstack.md

Other SDKs

其他SDK

PlatformLoad when…File
Dart / FlutterDart / Flutter (includes Drift ORM + Flutter Web)
references/sdks/powersync-dart.md
.NET.NET (MAUI, WPF, Console)
references/sdks/powersync-dotnet.md
KotlinKotlin (Android, JVM, iOS, macOS, watchOS, tvOS)
references/sdks/powersync-kotlin.md
SwiftSwift / iOS / macOS (includes GRDB ORM)
references/sdks/powersync-swift.md
平台适用场景文件
Dart / FlutterDart / Flutter(包含Drift ORM + Flutter Web)
references/sdks/powersync-dart.md
.NET.NET(MAUI、WPF、控制台应用)
references/sdks/powersync-dotnet.md
KotlinKotlin(Android、JVM、iOS、macOS、watchOS、tvOS)
references/sdks/powersync-kotlin.md
SwiftSwift / iOS / macOS(包含GRDB ORM)
references/sdks/powersync-swift.md

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
    powersync
    CLI commands. See
    references/powersync-cli.md
    for usage.
  • 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.
  • id
    column
    — never define
    id
    in a PowerSync table schema; it is created automatically as
    TEXT PRIMARY KEY
    .
  • No boolean/date column types — use
    column.integer
    (0/1) for booleans and
    column.text
    (ISO string) for dates.
  • connect()
    is fire-and-forget
    — do not
    await connect()
    expecting data to be ready. Use
    waitForFirstSync()
    if you need to wait.
  • transaction.complete()
    is mandatory
    — if it is never called, the upload queue stalls permanently.
  • disconnectAndClear()
    on logout
    disconnect()
    keeps local data;
    disconnectAndClear()
    wipes it. Always use
    disconnectAndClear()
    when switching users (this will however cause the client to do a full re-sync when connecting again).
  • Backend must return 2xx for validation errors — a 4xx response from
    uploadData
    blocks the upload queue permanently.
  • 使用CLI执行实例操作——部署配置、生成Schema、生成开发令牌、查看状态或管理云端/自行托管实例时,使用
    powersync
    CLI命令。具体用法请查阅
    references/powersync-cli.md
  • 优先使用同步流(Sync Streams)而非同步规则(Sync Rules)——新项目必须使用同步流(版本3配置)。同步规则为旧版功能;仅当现有项目已使用时才继续使用。
  • id
    ——绝不要在PowerSync表Schema中定义
    id
    ;它会自动创建为
    TEXT PRIMARY KEY
    类型。
  • 禁止使用布尔/日期列类型——布尔值使用
    column.integer
    (0/1)表示,日期使用
    column.text
    (ISO字符串)表示。
  • connect()
    是“触发即遗忘”
    ——不要通过
    await connect()
    等待数据准备就绪。如果需要等待,请使用
    waitForFirstSync()
  • 必须调用
    transaction.complete()
    ——如果从未调用此方法,上传队列会永久停滞。
  • 登出时使用
    disconnectAndClear()
    ——
    disconnect()
    会保留本地数据;
    disconnectAndClear()
    会清除本地数据。切换用户时请始终使用
    disconnectAndClear()
    (但这会导致客户端再次连接时执行全量重新同步)。
  • 后端对验证错误需返回2xx状态码——
    uploadData
    返回4xx响应会导致上传队列永久阻塞。