diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..9c3fd93
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,86 @@
+name: Test
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+
+jobs:
+ backend:
+ name: Backend and connector tests
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: backend
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: pnpm/action-setup@v4
+ with:
+ package_json_file: backend/package.json
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: pnpm
+ cache-dependency-path: backend/pnpm-lock.yaml
+
+ - run: pnpm install --frozen-lockfile
+ - run: pnpm check
+ - run: pnpm test
+
+ example-client:
+ name: Type-check connectors against the PowerSync SDK
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: example-client
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: pnpm/action-setup@v4
+ with:
+ package_json_file: example-client/package.json
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: pnpm
+ cache-dependency-path: example-client/pnpm-lock.yaml
+
+ - run: pnpm install --frozen-lockfile
+ - run: pnpm check
+
+ supabase:
+ name: Supabase Edge Function tests
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: supabase/setup-cli@v1
+ with:
+ version: 2.98.2
+
+ - uses: denoland/setup-deno@v2
+ with:
+ deno-version: v2.x
+
+ - name: Start local Supabase
+ working-directory: backend
+ run: supabase start
+
+ - name: Serve functions
+ working-directory: backend
+ run: |
+ supabase functions serve > "$RUNNER_TEMP/functions.log" 2>&1 &
+ for i in $(seq 1 60); do
+ grep -q "Serving functions" "$RUNNER_TEMP/functions.log" && exit 0
+ sleep 2
+ done
+ cat "$RUNNER_TEMP/functions.log"
+ exit 1
+
+ - name: Run tests
+ working-directory: backend/supabase/functions/powersync-write
+ run: deno task test
diff --git a/README.md b/README.md
index 04ad770..d75744b 100644
--- a/README.md
+++ b/README.md
@@ -1,15 +1,15 @@
# PowerSync Reference Write Implementation
When your PowerSync app writes data using SQL INSERT, UPDATE, or DELETE statements,
-PowerSync automatically queues these mutations for processing using the `uploadData` function.
+PowerSync automatically queues these mutations and passes them to the upload callback you give `connect()`.
-While there are no restrictions on the implementation of `uploadData` and the related write API,
+While there are no restrictions on the implementation of the upload callback and the related write API,
this repository provides a client connector and two implementations of the write API for most simple use cases.
It provides extension points that will allow you to customize
the behavior to your own requirements, or you can modify it to suit your specific case.
- [backend/shared/powersync-reference-write-api.openapi.yaml](backend/shared/powersync-reference-write-api.openapi.yaml) provides a simple but flexible API definition that serves as a contract between the client connector and either backend.
-- A [client connector](example-client/src/PowersyncConnector.ts) implementing `uploadData` handles most common workflows. It will marshal queued changes to the format specified by the API definition. A [single-file client connector](example-client/src/PowersyncConnector.singlefile.ts) is provided for ease of copy-paste.
+- A [client connector](example-client/src/PowersyncConnector.ts) providing the upload callback handles most common workflows. It will marshal queued changes to the format specified by the API definition. A [single-file client connector](example-client/src/PowersyncConnector.singlefile.ts) is provided for ease of copy-paste.
- The write API (`POST /api/data`) accepts queued transactions from the client connector and applies them to your source database. Choose the [standalone Express backend](backend/standalone/README.md), or, for Supabase apps, the [Supabase Edge Function](backend/supabase/README.md), which implements the same write API and enforces your existing RLS policies. Both use the [shared core](backend/shared), which contains the transaction processor and adapters for Postgres, MongoDB, MySQL, and SQL Server.
The green blocks are provided by this repository; click them to explore the code. Solid arrows
@@ -20,7 +20,7 @@ Choose one backend to serve the write API (`POST /api/data`).
flowchart TB
subgraph app["Your app"]
sdk["PowerSync SDK
Local database and upload queue"]
- connector["Client connector
uploadData()"]
+ connector["Client connector
upload"]
sdk -->|Queued local writes| connector
end
@@ -120,12 +120,22 @@ Startup checks the database type, connection string, fatal-error policy, and ver
### 4. Connect your app
-Copy a client connector from [example-client](example-client/README.md) into your app. Configure
-its write API URL, PowerSync instance URL, and token retrieval, then pass it to your existing
-PowerSync database's `connect()` method. The client connector implements:
+Copy a client connector from [example-client](example-client/README.md) into your app and set its
+write API URL. Then pass its `upload` callback to `connect()`, together with an `Authenticator`:
-- `fetchCredentials()`: credentials for the PowerSync sync connection. If your app is already reading data from PowerSync then you will have already implemented this function, we recommend that you keep your existing implementation and configure the Express backend to trust the same issuers - see [auth setup](docs/auth/setup.md).
-- `uploadData()`: sends queued local transactions to `POST /api/data`.
+```ts
+const connector = new PowersyncConnector({ authenticator });
+await db.connect({ powerSyncEndpoint, authenticator, upload: connector.upload });
+```
+
+- `authenticator`: supplies tokens for the PowerSync sync connection, and the connector uses it for
+ write requests too. If your app already syncs with PowerSync, keep your existing authentication and
+ configure the Express backend to trust the same issuers; see [auth setup](docs/auth/setup.md).
+- `upload`: sends queued local transactions to `POST /api/data`.
+
+This needs `@powersync/web` 2.6.0 or `@powersync/react-native` 2.4.0 or later. If your app connects
+with a `PowerSyncBackendConnector`, see
+[migrating from a backend connector](example-client/README.md#migrating-from-a-backend-connector).
Use a URL reachable from the client device. `localhost` refers to that device, so another
computer or phone needs the Express backend's network address or a tunnel URL.
diff --git a/backend/shared/test/connector.test.ts b/backend/shared/test/connector.test.ts
index 70be696..b4cc7c3 100644
--- a/backend/shared/test/connector.test.ts
+++ b/backend/shared/test/connector.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('uuid', () => ({ v4: () => 'test-user' }));
vi.mock('../../../example-client/src/library/powersync/OpenAPITransport', () => ({
- AuthenticationError: class extends Error {},
+ AuthenticationError: class AuthenticationError extends Error {},
createOpenAPIClient: () => ({ transport: {} })
}));
vi.mock('../../../example-client/src/library/powersync/DemoConnectorConfig', () => ({
@@ -20,8 +20,21 @@ const splitPath = '../../../example-client/src/PowersyncConnector.ts';
const singlePath = '../../../example-client/src/PowersyncConnector.singlefile.ts';
const { PowersyncConnector: Split } = await import(new URL(splitPath, import.meta.url).href);
const { PowersyncConnector: Single } = await import(new URL(singlePath, import.meta.url).href);
+const { AuthenticationError } = await import(
+ new URL('../../../example-client/src/library/powersync/OpenAPITransport.ts', import.meta.url).href
+);
+
+function stubAuthenticator() {
+ return {
+ resolveCredentials: vi.fn(async () => 'token'),
+ invalidateCredentials: vi.fn()
+ };
+}
-beforeEach(() => vi.stubGlobal('localStorage', { getItem: () => 'user' }));
+beforeEach(() => {
+ vi.unstubAllGlobals();
+ vi.stubGlobal('localStorage', { getItem: () => 'user' });
+});
for (const [name, Connector] of [
['split', Split],
@@ -29,7 +42,7 @@ for (const [name, Connector] of [
] as const) {
describe(`${name} connector queue completion`, () => {
async function upload(results: unknown[], decision: unknown = 'retain') {
- const connector = new Connector();
+ const connector = new Connector({ authenticator: stubAuthenticator() });
const hook = vi.fn(async () => {
if (decision instanceof Error) throw decision;
return decision;
@@ -65,7 +78,7 @@ for (const [name, Connector] of [
};
let error: unknown;
try {
- await connector.uploadData(database as any);
+ await connector.upload({ database: database as any });
} catch (e) {
error = e;
}
@@ -131,3 +144,56 @@ for (const [name, Connector] of [
});
});
}
+
+describe('write API authentication failure', () => {
+ const database = (complete = vi.fn(async () => {})) => ({
+ complete,
+ db: {
+ getClientId: async () => 'client',
+ async *getCrudTransactions() {
+ yield { crud: [{ id: '1', table: 'items', op: 'PUT' }], complete };
+ }
+ }
+ });
+
+ it.each([
+ [
+ 'split',
+ (connector: any) =>
+ Object.assign(connector, {
+ getWriteClient: async () =>
+ new WriteAPIClient({
+ transport: {
+ postTransactionBatch: async () => {
+ throw new AuthenticationError('Authentication failed (401)');
+ }
+ },
+ userId: 'user',
+ clientId: 'client'
+ })
+ }),
+ Split
+ ],
+ [
+ 'single',
+ () =>
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify({ message: 'Unauthorized' }), { status: 401 }))
+ ),
+ Single
+ ]
+ ] as const)(
+ '%s connector invalidates credentials on 401 and keeps the transaction queued',
+ async (_, stub, Connector) => {
+ const authenticator = stubAuthenticator();
+ const connector = new Connector({ authenticator });
+ stub(connector);
+ const { complete, db } = database();
+
+ await expect(connector.upload({ database: db as any })).rejects.toThrow();
+ expect(authenticator.invalidateCredentials).toHaveBeenCalledOnce();
+ expect(complete).not.toHaveBeenCalled();
+ }
+ );
+});
diff --git a/backend/shared/test/persister-ping.test.ts b/backend/shared/test/persister-ping.test.ts
index b2a17cc..487e3fc 100644
--- a/backend/shared/test/persister-ping.test.ts
+++ b/backend/shared/test/persister-ping.test.ts
@@ -40,7 +40,8 @@ vi.mock('mongodb', () => ({
MongoClient: class {
async connect() {}
db() {
- return { command: db.mongoCommand };
+ // createMongoPersister discovers collection validators at startup.
+ return { command: db.mongoCommand, listCollections: () => ({ toArray: async () => [] }) };
}
}
}));
diff --git a/backend/supabase/README.md b/backend/supabase/README.md
index 4335078..b7beffe 100644
--- a/backend/supabase/README.md
+++ b/backend/supabase/README.md
@@ -64,7 +64,7 @@ create policy "Owners manage their lists" on public.lists
> A write that a policy or missing grant denies returns `retryable_error` for the whole
> transaction. The client connector keeps it queued and retries, so a mistake in a policy or grant does not
> lose user writes, but it blocks that user's later uploads until the write succeeds. Have your
-> client connector's `uploadData` give up after a number of retries and dead-letter or discard the
+> client connector give up after a number of retries and dead-letter or discard the
> transaction. The Express backend instead returns a fatal `UNAUTHORIZED` that stays queued; see
> [error handling](../../docs/error-handling.md).
>
@@ -141,40 +141,40 @@ Supabase Auth tokens; see PowerSync's
### Using Supabase Auth in the connector
-Pass your app's supabase-js client to the copied connector and read the session on every call.
-Do not keep the connector's token cache: supabase-js refreshes the session itself, and the cache
-is cleared only after a rejected write, so sync would keep receiving an expired token. In
-`PowersyncConnector.ts`, replace `fetchCredentials()`, `fetchAuthToken()`, and `getAuthToken()`:
+Use an `Authenticator` that reads the access token from your app's supabase-js client, and pass it
+to both `connect()` and the connector. The SDK isn't guaranteed to cache tokens, so cache the token
+and clear the cache in `invalidateCredentials()`. PowerSync calls `invalidateCredentials()` 30
+seconds before the token expires, and the connector calls it when the write API rejects the token.
+The next `getSession()` call then returns a valid session: in current supabase-js versions, it
+refreshes the session when it expires within 90 seconds.
```ts
-constructor(private readonly supabase: SupabaseClient) {
- // existing setup
-}
-
-async fetchCredentials() {
- const session = await this.getSession();
- return {
- endpoint: this.config.powersyncUrl,
- token: session.access_token,
- expiresAt: session.expires_at ? new Date(session.expires_at * 1000) : undefined
- };
-}
-
-private async getSession() {
- const { data: { session }, error } = await this.supabase.auth.getSession();
- if (!session || error) throw new Error('Not signed in to Supabase');
- return session;
-}
-
-// Write requests call this through the transport.
-private async getAuthToken(): Promise {
- return (await this.getSession()).access_token;
-}
+import type { SupabaseClient } from '@supabase/supabase-js';
+import type { Authenticator } from '@powersync/web';
+
+declare const supabase: SupabaseClient; // your app's client
+
+let cachedToken: string | null = null;
+
+const authenticator: Authenticator = {
+ async resolveCredentials() {
+ if (!cachedToken) {
+ const { data: { session }, error } = await supabase.auth.getSession();
+ if (!session || error) throw new Error('Not signed in to Supabase');
+ cachedToken = session.access_token;
+ }
+ return cachedToken;
+ },
+ invalidateCredentials() {
+ cachedToken = null;
+ }
+};
+
+const connector = new PowersyncConnector({ authenticator });
+await db.connect({ powerSyncEndpoint, authenticator, upload: connector.upload });
```
-The single-file connector has the same methods; use `POWERSYNC_URL` instead of
-`this.config.powersyncUrl`. Remove the now-unused `_authToken` field, including its reset in
-`onTransportError()`. Uploads, batching, and error handling are unchanged.
+Uploads, batching, and error handling are unchanged.
## Customize
diff --git a/backend/supabase/functions/powersync-write/rls.ts b/backend/supabase/functions/powersync-write/rls.ts
index 554d98c..ad6a994 100644
--- a/backend/supabase/functions/powersync-write/rls.ts
+++ b/backend/supabase/functions/powersync-write/rls.ts
@@ -22,6 +22,7 @@ export async function asAuthenticatedUser(client: PG.PoolClient, auth: AuthConte
*/
export function permissionErrorsRetryable(persister: Persister): Persister {
return {
+ ping: () => persister.ping(),
async updateBatch(batch, auth) {
try {
await persister.updateBatch(batch, auth);
diff --git a/backend/supabase/tests/powersync-write/connector.test.ts b/backend/supabase/tests/powersync-write/connector.test.ts
index 0d16856..56a2ef1 100644
--- a/backend/supabase/tests/powersync-write/connector.test.ts
+++ b/backend/supabase/tests/powersync-write/connector.test.ts
@@ -3,7 +3,7 @@ import { admin, applyTestSchema, FUNCTION_URL, listRow, signUp } from './helpers
/**
* Runs the unchanged single-file example connector against the function. Only its BACKEND_URL
- * and AUTH_TOKEN constants are replaced.
+ * constant is replaced. The user's Supabase session token comes from an Authenticator.
*/
Deno.test({
name: 'example connector uploads through the function URL',
@@ -14,8 +14,7 @@ Deno.test({
const user = await signUp('connector');
const source = await Deno.readTextFile(new URL('../../../../example-client/src/PowersyncConnector.singlefile.ts', import.meta.url));
const configured = source
- .replace(/^const BACKEND_URL = .*$/m, `const BACKEND_URL = ${JSON.stringify(FUNCTION_URL)};`)
- .replace(/^const AUTH_TOKEN = .*$/m, `const AUTH_TOKEN = ${JSON.stringify(user.token)};`);
+ .replace(/^const BACKEND_URL = .*$/m, `const BACKEND_URL = ${JSON.stringify(FUNCTION_URL)};`);
const path = await Deno.makeTempFile({ suffix: '.ts' });
await Deno.writeTextFile(path, configured);
@@ -40,7 +39,8 @@ Deno.test({
};
try {
- await new PowersyncConnector().uploadData(database);
+ const authenticator = { resolveCredentials: async () => user.token };
+ await new PowersyncConnector({ authenticator }).upload({ database });
assertEquals(completed, 1);
assertEquals(await listRow(list), { name: 'From connector', owner_id: user.id });
} finally {
diff --git a/backend/supabase/tests/powersync-write/rls.test.ts b/backend/supabase/tests/powersync-write/rls.test.ts
index 215eab2..5370786 100644
--- a/backend/supabase/tests/powersync-write/rls.test.ts
+++ b/backend/supabase/tests/powersync-write/rls.test.ts
@@ -5,6 +5,7 @@ import { permissionErrorsRetryable } from '../../functions/powersync-write/rls.t
const auth = { sub: 'user', claims: {} };
const failing = (error: Error): Persister => ({
+ ping: () => Promise.resolve(),
updateBatch: () => Promise.reject(error)
});
@@ -17,5 +18,15 @@ Deno.test('permission errors from the persister become retryable', async () => {
Deno.test('other persister errors pass through unchanged', async () => {
const fatal = new FatalOperationError('CHECK_VIOLATION', 'bad value');
assertEquals(await assertRejects(() => permissionErrorsRetryable(failing(fatal)).updateBatch([], auth)), fatal);
- await permissionErrorsRetryable({ updateBatch: () => Promise.resolve() }).updateBatch([], auth);
+ await permissionErrorsRetryable({ ping: () => Promise.resolve(), updateBatch: () => Promise.resolve() }).updateBatch([], auth);
+});
+
+Deno.test('ping passes through to the wrapped persister', async () => {
+ let pinged = 0;
+ const persister = permissionErrorsRetryable({
+ ping: () => Promise.resolve(void pinged++),
+ updateBatch: () => Promise.resolve()
+ });
+ await persister.ping();
+ assertEquals(pinged, 1);
});
diff --git a/docs/auth/development-tokens.md b/docs/auth/development-tokens.md
index cfcc261..f0a6148 100644
--- a/docs/auth/development-tokens.md
+++ b/docs/auth/development-tokens.md
@@ -31,5 +31,5 @@ Restart the Express backend after changing these.
## 3. Use the token
-In your copy of the connector, return the token from the private `fetchAuthToken()` method.
-Both `fetchCredentials()` (sync) and writes use it.
+Return the token from `fetchAuthToken()` in the demo authenticator; see the
+[example client](../../example-client/README.md#configure-and-connect). Both sync and writes use it.
diff --git a/docs/auth/providers.md b/docs/auth/providers.md
index 1814aa8..67efd63 100644
--- a/docs/auth/providers.md
+++ b/docs/auth/providers.md
@@ -3,10 +3,11 @@
Express backend settings that are specific to these providers. For everything else, see
[auth setup](setup.md).
-In the client connector you copied, return the provider's token from the private `fetchAuthToken()`
-method, which supplies both writes and `fetchCredentials()` (sync). Provider SDKs manage their
-own sessions, so you can drop the demo token cache in `getAuthToken()`. If sync and
-writes use different tokens, both must carry the same user ID in `sub`.
+In your app, replace the demo `Authenticator` from the [example client](../../example-client/README.md#configure-and-connect)
+with one whose `resolveCredentials()` returns the provider's token. The connector uses it for
+writes and PowerSync uses it for sync. Keep the demo's token cache, which `invalidateCredentials()`
+clears: the SDK isn't guaranteed to cache tokens. If sync and writes use different tokens, pass the
+connector its own authenticator. Both tokens must carry the same user ID in `sub`.
## Supabase
@@ -56,5 +57,6 @@ AUTH_AUTHORIZED_PARTIES=http://localhost:5173,https://yourapp.com
check, any token from your Clerk instance would be valid. Tokens with a missing or unlisted
`azp` are rejected, so apps whose tokens omit it need a custom verifier.
-In the connector, `getAuthToken()` returns `clerk.session.getToken()` for session tokens and
-`fetchCredentials()` returns `getToken({ template: '' })`.
+With session tokens for writes, use two authenticators: pass `connect()` one whose
+`resolveCredentials()` returns `clerk.session.getToken({ template: '' })`, and pass the
+connector one that returns `clerk.session.getToken()`. Give each its own token cache.
diff --git a/docs/single-file-connector-maintenance.md b/docs/single-file-connector-maintenance.md
index e88fb4f..19b9c9c 100644
--- a/docs/single-file-connector-maintenance.md
+++ b/docs/single-file-connector-maintenance.md
@@ -26,25 +26,26 @@ Preserve the modular client connector's runtime behavior and follow these requir
this API need a polyfill or their own UUID generator.
5. Define API types from the current OpenAPI contract, including discriminated result
unions and application-defined error codes. Preserve the contract's type constraints.
-6. Throw `AuthenticationError` for 401/403 responses so the connector clears its cached
- token. Preserve error-message parsing and fallback handling for other failures.
+6. Throw `AuthenticationError` for 401/403 responses so the connector calls the
+ authenticator's `invalidateCredentials()`. Preserve error-message parsing and fallback handling for other failures.
7. Keep `AppSchema.ts` separate from the connector.
8. Implement transport as a private connector method. Do not add a transport injection layer.
9. Omit the unused `clientId` request option and the modular `_writeClient` cache.
The single-file client connector calls its own transport method. Preserve any future
behavior that depends on the client ID.
-10. Keep a concise header covering dependencies, editable constants, demo token setup,
+10. Keep a concise header covering dependencies, editable constants, `connect()` wiring,
write API verification, PowerSync JWKS configuration, and identity-provider integration.
Include the setup links because users may copy the file without its README.
-11. Preserve the methods and override points: `uploadData`, `fetchCredentials`,
- `getBatchingConfig`, `onFatalTransaction`, `onRetryableError`, and `onTransportError`.
+11. Preserve the API and override points: the `{ authenticator }` constructor option, the
+ `upload` callback, `getBatchingConfig`, `onFatalTransaction`, `onRetryableError`, and
+ `onTransportError`. Take write tokens from `authenticator.resolveCredentials()`.
Keep shared behavior documented consistently in both connector versions.
Write comments that explain behavior, configuration, or constraints. Avoid repeated
reassurances, all-caps warnings, metaphors, and accounts of earlier design proposals.
Update the example-client README if the file layout changes. The example client remains
-reference code without its own package manifest, build step, or test suite.
+reference code without a build step or test suite; its `package.json` only type-checks it.
## Fatal-error handling
diff --git a/example-client/.env.example b/example-client/.env.example
index 3f6ee00..ed9d6ad 100644
--- a/example-client/.env.example
+++ b/example-client/.env.example
@@ -4,7 +4,7 @@
VITE_BACKEND_URL=http://localhost:6060
VITE_POWERSYNC_URL=
# Token for sync and writes, e.g. a session token copied from your auth provider. Real apps fetch
-# it from the provider instead; see fetchAuthToken() in PowersyncConnector.ts.
+# it from the provider instead; see the demo authenticator in README.md.
VITE_POWERSYNC_TOKEN=
# Transaction batching. There is one upload path and one endpoint (POST /api/data), which always
diff --git a/example-client/README.md b/example-client/README.md
index a53e3c4..2f2147e 100644
--- a/example-client/README.md
+++ b/example-client/README.md
@@ -1,8 +1,11 @@
# Example client
-Copy one of these TypeScript client connectors into your PowerSync app. This directory
-has no package manifest or runnable UI. Each client connector sends local transactions to the write API; the
-PowerSync SDK handles the separate sync connection.
+Copy one of these TypeScript client connectors into your PowerSync app. This directory has no
+runnable UI; its `package.json` only type-checks the connectors (`pnpm check`). Each client
+connector sends local transactions to the write API; the PowerSync SDK handles the separate sync
+connection.
+
+The connectors need `@powersync/web` 2.6.0 or `@powersync/react-native` 2.4.0 or later.
## Choose a client connector
@@ -28,7 +31,7 @@ The modular client connector reads these variables through `import.meta.env`. Ad
| Variable | Meaning |
| --- | --- |
| `VITE_BACKEND_URL` | Write API base URL without a trailing slash, e.g. `http://localhost:6060` |
-| `VITE_POWERSYNC_URL` | Your PowerSync instance URL |
+| `VITE_POWERSYNC_URL` | Your PowerSync instance URL, passed to `connect()` |
| `VITE_POWERSYNC_TOKEN` | Demo token for sync and writes; replace `fetchAuthToken()` in real apps |
| `VITE_BATCH_MAX_TRANSACTIONS` | Transactions per request; use 1–50 (default 1) |
| `VITE_BATCH_MAX_OPERATIONS` | Operation threshold for collecting transactions (default 1000) |
@@ -40,37 +43,105 @@ uploads one transaction per request. The write API rejects batches larger than 5
by the last transaction collected because the connector does not split transactions.
The single-file client connector uses constants at the top instead of environment variables.
-Set its URLs, batch thresholds, and timeout there.
+Set its write API URL, batch thresholds, and timeout there.
-After adapting authentication, connect your initialized PowerSync database:
+Connect your initialized PowerSync database with an `Authenticator` and the connector's `upload`
+callback. This demo authenticator returns the fixed `VITE_POWERSYNC_TOKEN`:
```ts
+import type { Authenticator } from '@powersync/web';
import { PowersyncConnector } from './PowersyncConnector';
+import { readDemoConfig } from './library/powersync/DemoConnectorConfig';
+
+const config = readDemoConfig();
+
+// Replace with your auth provider's token retrieval.
+async function fetchAuthToken(): Promise {
+ if (!config.authToken) {
+ throw new Error('No auth token. Set VITE_POWERSYNC_TOKEN or replace fetchAuthToken().');
+ }
+ return config.authToken;
+}
+
+let cachedToken: string | null = null;
+
+const authenticator: Authenticator = {
+ async resolveCredentials() {
+ cachedToken ??= await fetchAuthToken();
+ return cachedToken;
+ },
+ // Called after PowerSync or the write API rejects the token, and before it expires.
+ invalidateCredentials() {
+ cachedToken = null;
+ }
+};
+
+const connector = new PowersyncConnector({ authenticator });
+await db.connect({ powerSyncEndpoint: config.powersyncUrl, authenticator, upload: connector.upload });
+```
+
+`db` is your existing PowerSync database instance. The authenticator supplies the token for sync,
+and the connector uses it for writes. For the single-file version, change the import path and
+pass your PowerSync instance URL as `powerSyncEndpoint`.
+
+## Migrating from a Backend Connector
+
+If your app connects with a `PowerSyncBackendConnector`, move its `fetchCredentials()` into an
+`Authenticator` and replace its `uploadData()` with the connector's `upload` callback. An app
+can't pass both a backend connector and an `upload` callback to `connect()`.
+
+Before:
+
+```ts
+class MyConnector implements PowerSyncBackendConnector {
+ async fetchCredentials() {
+ return { endpoint: POWERSYNC_URL, token: await fetchAuthToken() };
+ }
-await db.connect(new PowersyncConnector());
+ async uploadData(database: CommonPowerSyncDatabase) {
+ // ...
+ }
+}
+
+await db.connect(new MyConnector());
+```
+
+After:
+
+```ts
+const authenticator: Authenticator = {
+ async resolveCredentials() {
+ return fetchAuthToken();
+ }
+};
+
+const connector = new PowersyncConnector({ authenticator });
+await db.connect({ powerSyncEndpoint: POWERSYNC_URL, authenticator, upload: connector.upload });
```
-`db` is your existing PowerSync database instance. For the single-file version, change the
-import path. `fetchCredentials()` supplies the sync token; `uploadData()` sends writes.
+The SDK isn't guaranteed to cache tokens from an `Authenticator`. Cache the token in
+`resolveCredentials()` and clear the cache in `invalidateCredentials()`, as in the demo above. `resolveCredentials()` returns only the token,
+so drop any `expiresAt`.
## Authentication
Neither backend issues tokens. Configure the Express backend to trust your token provider,
or use Supabase Auth with the Supabase Edge Function. Your PowerSync instance must trust
-the tokens used for sync. The demo `fetchAuthToken()` returns a fixed token (`VITE_POWERSYNC_TOKEN`, or
-`AUTH_TOKEN` in the single-file connector), such as a session token copied from your provider.
-Both sync and writes reuse it.
-
-For a provider integration, edit the private `fetchAuthToken()` method in your copied connector.
-See [Supabase and Clerk](../docs/auth/providers.md). If using different tokens for sync and writes,
-also adapt `fetchCredentials()`, keeping the same user ID in both tokens.
+the tokens used for sync. The demo authenticator returns a fixed token, such as a session token
+copied from your provider. Both sync and writes use it.
+
+The connector takes write tokens from the authenticator you pass it. Each write request calls
+`resolveCredentials()`. After a 401 or 403 write response, the connector calls
+`invalidateCredentials()` and the upload is retried. For a provider integration, replace the demo
+authenticator; see [Supabase and Clerk](../docs/auth/providers.md). If writes need a different
+token from sync, pass the connector a second authenticator, keeping the same user ID in both tokens.
+
+Cache the token in your authenticator even if your provider SDK refreshes sessions itself, and
+clear the cache in `invalidateCredentials()`. The next `resolveCredentials()` call then gets the
+provider's current token. For Supabase, see
+[Using Supabase Auth in the connector](../backend/supabase/README.md#using-supabase-auth-in-the-connector).
The modular transport's token callback is `getAuthToken`; its timeout option is `timeoutMs`.
-The demo clears its cached token after a 401/403 write response. Provider SDKs should manage
-provider sessions without the demo cache. If your provider SDK refreshes sessions itself, remove
-the cache in `getAuthToken()` and read the session on each call; otherwise sync keeps using an
-expired token. For Supabase, see
-[Using Supabase Auth in the connector](../backend/supabase/README.md#using-supabase-auth-in-the-connector).
## Rejected writes
diff --git a/example-client/package.json b/example-client/package.json
new file mode 100644
index 0000000..59d3c15
--- /dev/null
+++ b/example-client/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "example-client",
+ "private": true,
+ "description": "Type-checks the reference connectors against the minimum supported PowerSync Web SDK. Not a runnable app.",
+ "type": "module",
+ "scripts": {
+ "check": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@powersync/common": "2.5.0",
+ "@powersync/web": "2.6.0",
+ "openapi-fetch": "^0.17.0",
+ "typescript": "^5.9.3",
+ "uuid": "^11.1.1",
+ "vite": "^7.3.8"
+ },
+ "packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee"
+}
diff --git a/example-client/pnpm-lock.yaml b/example-client/pnpm-lock.yaml
new file mode 100644
index 0000000..5af31ac
--- /dev/null
+++ b/example-client/pnpm-lock.yaml
@@ -0,0 +1,738 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@powersync/common':
+ specifier: 2.5.0
+ version: 2.5.0
+ '@powersync/web':
+ specifier: 2.6.0
+ version: 2.6.0(@powersync/common@2.5.0)(@powersync/shared-internals@1.6.0(@powersync/common@2.5.0))
+ openapi-fetch:
+ specifier: ^0.17.0
+ version: 0.17.0
+ typescript:
+ specifier: ^5.9.3
+ version: 5.9.3
+ uuid:
+ specifier: ^11.1.1
+ version: 11.1.1
+ vite:
+ specifier: ^7.3.8
+ version: 7.3.8
+
+packages:
+
+ '@esbuild/aix-ppc64@0.28.2':
+ resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/android-arm64@0.28.2':
+ resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/android-arm@0.28.2':
+ resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/android-x64@0.28.2':
+ resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/darwin-arm64@0.28.2':
+ resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/darwin-x64@0.28.2':
+ resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/freebsd-arm64@0.28.2':
+ resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/freebsd-x64@0.28.2':
+ resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/linux-arm64@0.28.2':
+ resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/linux-arm@0.28.2':
+ resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/linux-ia32@0.28.2':
+ resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/linux-loong64@0.28.2':
+ resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/linux-mips64el@0.28.2':
+ resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/linux-ppc64@0.28.2':
+ resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/linux-riscv64@0.28.2':
+ resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/linux-s390x@0.28.2':
+ resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/linux-x64@0.28.2':
+ resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/netbsd-arm64@0.28.2':
+ resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@esbuild/netbsd-x64@0.28.2':
+ resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/openbsd-arm64@0.28.2':
+ resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@esbuild/openbsd-x64@0.28.2':
+ resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/openharmony-arm64@0.28.2':
+ resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@esbuild/sunos-x64@0.28.2':
+ resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/win32-arm64@0.28.2':
+ resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/win32-ia32@0.28.2':
+ resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/win32-x64@0.28.2':
+ resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
+ '@journeyapps/wa-sqlite@2.0.10':
+ resolution: {integrity: sha512-6Wo5ZijOc4/6M9u+MDsJdW8zDCdrct/p+7LcG7S7CT5YKu42j6lshMfUvgtGYMaZeuH7rpQHULZupPTQFqbS0w==}
+
+ '@powersync/common@2.5.0':
+ resolution: {integrity: sha512-kMlAfrQddGIAFuO7qCyYxf2yxAKdCrwGany9VcHs8Rx9f5KuqxqaCikzq/SC4Evf/f/sTS5eIwczZPPQboTjxw==}
+
+ '@powersync/shared-internals@1.6.0':
+ resolution: {integrity: sha512-UduDSVv9qfonIezOklBUR6c3KNlwOQ8/XCsTDwrBUXnVv4wmAZuIDO7C2hX2KKcQGKn+rU0Z5R9uPtgl1uK7Vg==}
+ peerDependencies:
+ '@powersync/common': ^2.5.0
+ peerDependenciesMeta:
+ '@powersync/common':
+ optional: true
+
+ '@powersync/web@2.6.0':
+ resolution: {integrity: sha512-/B8u/sPHyNiPH1bj+vOfN/9sHlbp9lwQGtS6BHJJjqWlhBaUxzh4xQMydyQcS6puHaDXzddpOlkZIvTLOTLMnw==}
+ hasBin: true
+ peerDependencies:
+ '@powersync/common': ^2.5.0
+ '@powersync/shared-internals': ^1.5.0
+
+ '@rollup/rollup-android-arm-eabi@4.68.4':
+ resolution: {integrity: sha512-8AfICPTDNFpsRltDrWzlX3iVEwHubamhXc10bjOJRCl4eZXj+BE25uCVMYzFpbcqfuxSfrt4VkSVL5QqiHoVDQ==}
+ cpu: [arm]
+ os: [android]
+
+ '@rollup/rollup-android-arm64@4.68.4':
+ resolution: {integrity: sha512-Vs4CxDXeCrCVNZ9jPnicohYT7aX7cxLzjMepkno/7f1zFhC80OUsKHM03BJsusLfYnjKrUe7D8vPvQNdD+rjCg==}
+ cpu: [arm64]
+ os: [android]
+
+ '@rollup/rollup-android-x64@4.68.4':
+ resolution: {integrity: sha512-EEytXPqw9k5OIyx1Cou+Xg8XhTwtWW31WIGq1cWTpX05ek6STIprxJ5wY6cOEZAk5sjXM/mE2/JohNhtUiPukg==}
+ cpu: [x64]
+ os: [android]
+
+ '@rollup/rollup-darwin-arm64@4.68.4':
+ resolution: {integrity: sha512-eRYMGvFdL3TKnaXlacxifKMltpLxehT0XghbV5pPfzJUNCc+psia9rg/scZZPfeDK+VKpSZx9VoMz236yeYEaQ==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rollup/rollup-darwin-x64@4.68.4':
+ resolution: {integrity: sha512-w+E1P+Ul1PgoAiH22tcONSEyx+3VjUcSIZeqr1QSOSC5vvawduMVtgD1ZtfQsPHkpTN/VJekrgN3JL2+YKhaDQ==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rollup/rollup-freebsd-arm64@4.68.4':
+ resolution: {integrity: sha512-nukgdVNAx7X07qu8nZjJwuCRW/yDjLIio83yXhKUkuUUXTlmEGjVRN+XxrzxnkhiTRfHnqC/OYAga3t7vMQkAw==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@rollup/rollup-freebsd-x64@4.68.4':
+ resolution: {integrity: sha512-o5vn+twqv2XwxEpseC76YCNXpCXoRlPmr+ZYpSnmlxbFh5kdHysap9V93cS1hzAXtK6xuXa5kdtS+/8rkUfs4Q==}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rollup/rollup-linux-arm-gnueabihf@4.68.4':
+ resolution: {integrity: sha512-b2w9laiL8oWofYqGF+ABzin9wNMPxzHRD21EIPJ5A0iniq19d3flE4UP7uZKl1gj+d3Kv/bt1htVUSzI0bE1TQ==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/rollup-linux-arm-musleabihf@4.68.4':
+ resolution: {integrity: sha512-Ao858LxFnvGrn4qbin3rr+LmEhOrF9pQKgzEnT14f9KjOpytd5smOuj7OOtkejJ7YVb5cBdPpYdT1zjwNcNq9g==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/rollup-linux-arm64-gnu@4.68.4':
+ resolution: {integrity: sha512-B78SoWLJeAleSOIDFZ+twb+7DoBla0g73LrdkxlkNwicAsrLfHeYX+NcPlOmxZ3Z8vKVvj0J/kmIMzEaqbQNGg==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/rollup-linux-arm64-musl@4.68.4':
+ resolution: {integrity: sha512-IK0JVhVLGer5AlmgU0eMbfuldxO1wNACZBwyq+ot9UW899hhkWPcO3k0eIrNlqmuWrySvMtzr7GK9xkbNekOTQ==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/rollup-linux-loong64-gnu@4.68.4':
+ resolution: {integrity: sha512-6MoYXMYy+6eqtVesSNehfsS3LY4A0P8MpHfhcnMkVsWVhaLv0vvuCj2EGkanchIoyHxAmxY+aR3ankaTkokC2A==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/rollup-linux-loong64-musl@4.68.4':
+ resolution: {integrity: sha512-mo+MC3fHiG4EOdtp7uGSvBv/4hKpqxhV16QGpXn2D0mTBBiOW6hGIOXUK7nck8THlURRWjYdtUPvvJfxHKZ/2w==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/rollup-linux-ppc64-gnu@4.68.4':
+ resolution: {integrity: sha512-uBRu6ztHsmoW/10bPsOVbhW8ie4Puw6+CQD/XLRGqr3ugv6pRNm3b4vebiwouhCgkjJ/ItJdqHKJ3mVhpr/wQA==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/rollup-linux-ppc64-musl@4.68.4':
+ resolution: {integrity: sha512-XNY+QlYWmhqzeiMdOKjziVnx6aP5cXSxbk4rDqbb+MH2IcNiIZWX1wPRfAVV6ntiM17XHJJ2WUNcxnglDNH69A==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/rollup-linux-riscv64-gnu@4.68.4':
+ resolution: {integrity: sha512-agahuMApMIOQgJMNEaJNtQRD+iUllqAvkF/V7WutWaBLTSeMgFd0urEo6m1scFmG0Cd+2zIPvnu2SWcKeuSB1Q==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/rollup-linux-riscv64-musl@4.68.4':
+ resolution: {integrity: sha512-1N+ysuGmcw/PAC4E5/vpotbjC7zHBMqOMJ+kdjkuvVGbj4Mkzu1/cNI4IMaU27VP6MWded1fQAU9ME2m/JmiUA==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/rollup-linux-s390x-gnu@4.68.4':
+ resolution: {integrity: sha512-ZO0fVys5Rtut3W0FcpKl/T/CTuTgaujErjanLJHVSmqhWaXnPr1u1VAinHPb8ash+cHA8yMX4QnRbmXhrrXfAg==}
+ cpu: [s390x]
+ os: [linux]
+
+ '@rollup/rollup-linux-x64-gnu@4.68.4':
+ resolution: {integrity: sha512-a4T4Ji3Is/TCh4rUuV6ehDdSMp3hxLH/v7mP4VT0kVB90Hfr9GUHVAiJhiJ3iy+tJ4qpvIG4haP+HpivOyWYpw==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/rollup-linux-x64-musl@4.68.4':
+ resolution: {integrity: sha512-I4FcDk1+t2w7/JwKakDbhOKvtP07Q8Y/jqaTTdgVklmfqTqmTwtIk254iSP4iCgXgQWThKm8CN67mDzPGDnpqw==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/rollup-openbsd-x64@4.68.4':
+ resolution: {integrity: sha512-kpekXvZs3E/21ps5tUiPbQggi4C8bCx4jBl2eAIaVTerC7eDLWJunZ6nRw3/K4r20E5Z5f1bmbrfSS6H8GRv+A==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/rollup-openharmony-arm64@4.68.4':
+ resolution: {integrity: sha512-mrnM4nr22FidljIL4vGK1htFcxPNCjLK/g2LQvgpBbq8pKL/zHY1czntTDbtYjoaYWVFu+XX0P2r2h/7zwWlIw==}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rollup/rollup-win32-arm64-msvc@4.68.4':
+ resolution: {integrity: sha512-xKF6HKrBdrb3jpGFlGAGtNF6nMu/TGdnVO38durZTMQUaduIqH/aDIjyi7SXmXNDUXTfTMUEIGVwPQ5FuMhCLQ==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rollup/rollup-win32-ia32-msvc@4.68.4':
+ resolution: {integrity: sha512-uu45X0jgiXEab6vcoWuPQLqhBPKUCZkXc+gv0oTI78mhn5DnQC2WGvNJ/s6Cnc68PvB/8vAtlE2dIHrpx/wySw==}
+ cpu: [ia32]
+ os: [win32]
+
+ '@rollup/rollup-win32-x64-gnu@4.68.4':
+ resolution: {integrity: sha512-+sVn72CSCbAemlPieSHWpBsJR5vkWH/xQM0Px0loHUhscMNl3CuH0UwTHuzCIaamlv+ZTi1V44jEKQ45FUaNwg==}
+ cpu: [x64]
+ os: [win32]
+
+ '@rollup/rollup-win32-x64-msvc@4.68.4':
+ resolution: {integrity: sha512-/eMzhxPPUGd5vjHdaNtvxHbblmoe+DyvPnJkZ4uQrDlVq9PQSd8br4pWwamycwRcLoNEzXwFy2mzcGoZTYqU5A==}
+ cpu: [x64]
+ os: [win32]
+
+ '@types/estree@1.0.10':
+ resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==}
+
+ comlink@4.4.2:
+ resolution: {integrity: sha512-OxGdvBmJuNKSCMO4NTl1L47VRp6xn2wG4F/2hYzB6tiCb709otOxtEYCSvK80PtjODfXXZu8ds+Nw5kVCjqd2g==}
+
+ commander@12.1.0:
+ resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}
+ engines: {node: '>=18'}
+
+ esbuild@0.28.2:
+ resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ fdir@6.5.0:
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ fsevents@2.3.3:
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ nanoid@3.3.20:
+ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ openapi-fetch@0.17.0:
+ resolution: {integrity: sha512-PsbZR1wAPcG91eEthKhN+Zn92FMHxv+/faECIwjXdxfTODGSGegYv0sc1Olz+HYPvKOuoXfp+0pA2XVt2cI0Ig==}
+
+ openapi-typescript-helpers@0.1.0:
+ resolution: {integrity: sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw==}
+
+ picocolors@1.1.1:
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ picomatch@4.0.7:
+ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
+ engines: {node: '>=12'}
+
+ postcss@8.5.33:
+ resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ rollup@4.68.4:
+ resolution: {integrity: sha512-5acdO1/M9urvHQuZVkoOt8JWQH6XxCnFnox1qodE39qkXaML67S2E7MhHDgx3pQYycM1A5dRJwahYMDLO9a3Yg==}
+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}
+ hasBin: true
+
+ source-map-js@1.2.2:
+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ engines: {node: '>=0.10.0'}
+
+ tinyglobby@0.2.17:
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ typescript@5.9.3:
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ uuid@11.1.1:
+ resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
+ hasBin: true
+
+ vite@7.3.8:
+ resolution: {integrity: sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ lightningcss: ^1.21.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+snapshots:
+
+ '@esbuild/aix-ppc64@0.28.2':
+ optional: true
+
+ '@esbuild/android-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/android-arm@0.28.2':
+ optional: true
+
+ '@esbuild/android-x64@0.28.2':
+ optional: true
+
+ '@esbuild/darwin-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/darwin-x64@0.28.2':
+ optional: true
+
+ '@esbuild/freebsd-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/freebsd-x64@0.28.2':
+ optional: true
+
+ '@esbuild/linux-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/linux-arm@0.28.2':
+ optional: true
+
+ '@esbuild/linux-ia32@0.28.2':
+ optional: true
+
+ '@esbuild/linux-loong64@0.28.2':
+ optional: true
+
+ '@esbuild/linux-mips64el@0.28.2':
+ optional: true
+
+ '@esbuild/linux-ppc64@0.28.2':
+ optional: true
+
+ '@esbuild/linux-riscv64@0.28.2':
+ optional: true
+
+ '@esbuild/linux-s390x@0.28.2':
+ optional: true
+
+ '@esbuild/linux-x64@0.28.2':
+ optional: true
+
+ '@esbuild/netbsd-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/netbsd-x64@0.28.2':
+ optional: true
+
+ '@esbuild/openbsd-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/openbsd-x64@0.28.2':
+ optional: true
+
+ '@esbuild/openharmony-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/sunos-x64@0.28.2':
+ optional: true
+
+ '@esbuild/win32-arm64@0.28.2':
+ optional: true
+
+ '@esbuild/win32-ia32@0.28.2':
+ optional: true
+
+ '@esbuild/win32-x64@0.28.2':
+ optional: true
+
+ '@journeyapps/wa-sqlite@2.0.10': {}
+
+ '@powersync/common@2.5.0': {}
+
+ '@powersync/shared-internals@1.6.0(@powersync/common@2.5.0)':
+ optionalDependencies:
+ '@powersync/common': 2.5.0
+
+ '@powersync/web@2.6.0(@powersync/common@2.5.0)(@powersync/shared-internals@1.6.0(@powersync/common@2.5.0))':
+ dependencies:
+ '@journeyapps/wa-sqlite': 2.0.10
+ '@powersync/common': 2.5.0
+ '@powersync/shared-internals': 1.6.0(@powersync/common@2.5.0)
+ comlink: 4.4.2
+ commander: 12.1.0
+
+ '@rollup/rollup-android-arm-eabi@4.68.4':
+ optional: true
+
+ '@rollup/rollup-android-arm64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-android-x64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-darwin-arm64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-darwin-x64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-freebsd-arm64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-freebsd-x64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-arm-gnueabihf@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-arm-musleabihf@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-arm64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-arm64-musl@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-loong64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-loong64-musl@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-ppc64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-ppc64-musl@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-riscv64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-riscv64-musl@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-s390x-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-x64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-linux-x64-musl@4.68.4':
+ optional: true
+
+ '@rollup/rollup-openbsd-x64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-openharmony-arm64@4.68.4':
+ optional: true
+
+ '@rollup/rollup-win32-arm64-msvc@4.68.4':
+ optional: true
+
+ '@rollup/rollup-win32-ia32-msvc@4.68.4':
+ optional: true
+
+ '@rollup/rollup-win32-x64-gnu@4.68.4':
+ optional: true
+
+ '@rollup/rollup-win32-x64-msvc@4.68.4':
+ optional: true
+
+ '@types/estree@1.0.10': {}
+
+ comlink@4.4.2: {}
+
+ commander@12.1.0: {}
+
+ esbuild@0.28.2:
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.28.2
+ '@esbuild/android-arm': 0.28.2
+ '@esbuild/android-arm64': 0.28.2
+ '@esbuild/android-x64': 0.28.2
+ '@esbuild/darwin-arm64': 0.28.2
+ '@esbuild/darwin-x64': 0.28.2
+ '@esbuild/freebsd-arm64': 0.28.2
+ '@esbuild/freebsd-x64': 0.28.2
+ '@esbuild/linux-arm': 0.28.2
+ '@esbuild/linux-arm64': 0.28.2
+ '@esbuild/linux-ia32': 0.28.2
+ '@esbuild/linux-loong64': 0.28.2
+ '@esbuild/linux-mips64el': 0.28.2
+ '@esbuild/linux-ppc64': 0.28.2
+ '@esbuild/linux-riscv64': 0.28.2
+ '@esbuild/linux-s390x': 0.28.2
+ '@esbuild/linux-x64': 0.28.2
+ '@esbuild/netbsd-arm64': 0.28.2
+ '@esbuild/netbsd-x64': 0.28.2
+ '@esbuild/openbsd-arm64': 0.28.2
+ '@esbuild/openbsd-x64': 0.28.2
+ '@esbuild/openharmony-arm64': 0.28.2
+ '@esbuild/sunos-x64': 0.28.2
+ '@esbuild/win32-arm64': 0.28.2
+ '@esbuild/win32-ia32': 0.28.2
+ '@esbuild/win32-x64': 0.28.2
+
+ fdir@6.5.0(picomatch@4.0.7):
+ optionalDependencies:
+ picomatch: 4.0.7
+
+ fsevents@2.3.3:
+ optional: true
+
+ nanoid@3.3.20: {}
+
+ openapi-fetch@0.17.0:
+ dependencies:
+ openapi-typescript-helpers: 0.1.0
+
+ openapi-typescript-helpers@0.1.0: {}
+
+ picocolors@1.1.1: {}
+
+ picomatch@4.0.7: {}
+
+ postcss@8.5.33:
+ dependencies:
+ nanoid: 3.3.20
+ picocolors: 1.1.1
+ source-map-js: 1.2.2
+
+ rollup@4.68.4:
+ dependencies:
+ '@types/estree': 1.0.10
+ optionalDependencies:
+ '@rollup/rollup-android-arm-eabi': 4.68.4
+ '@rollup/rollup-android-arm64': 4.68.4
+ '@rollup/rollup-android-x64': 4.68.4
+ '@rollup/rollup-darwin-arm64': 4.68.4
+ '@rollup/rollup-darwin-x64': 4.68.4
+ '@rollup/rollup-freebsd-arm64': 4.68.4
+ '@rollup/rollup-freebsd-x64': 4.68.4
+ '@rollup/rollup-linux-arm-gnueabihf': 4.68.4
+ '@rollup/rollup-linux-arm-musleabihf': 4.68.4
+ '@rollup/rollup-linux-arm64-gnu': 4.68.4
+ '@rollup/rollup-linux-arm64-musl': 4.68.4
+ '@rollup/rollup-linux-loong64-gnu': 4.68.4
+ '@rollup/rollup-linux-loong64-musl': 4.68.4
+ '@rollup/rollup-linux-ppc64-gnu': 4.68.4
+ '@rollup/rollup-linux-ppc64-musl': 4.68.4
+ '@rollup/rollup-linux-riscv64-gnu': 4.68.4
+ '@rollup/rollup-linux-riscv64-musl': 4.68.4
+ '@rollup/rollup-linux-s390x-gnu': 4.68.4
+ '@rollup/rollup-linux-x64-gnu': 4.68.4
+ '@rollup/rollup-linux-x64-musl': 4.68.4
+ '@rollup/rollup-openbsd-x64': 4.68.4
+ '@rollup/rollup-openharmony-arm64': 4.68.4
+ '@rollup/rollup-win32-arm64-msvc': 4.68.4
+ '@rollup/rollup-win32-ia32-msvc': 4.68.4
+ '@rollup/rollup-win32-x64-gnu': 4.68.4
+ '@rollup/rollup-win32-x64-msvc': 4.68.4
+ fsevents: 2.3.3
+
+ source-map-js@1.2.2: {}
+
+ tinyglobby@0.2.17:
+ dependencies:
+ fdir: 6.5.0(picomatch@4.0.7)
+ picomatch: 4.0.7
+
+ typescript@5.9.3: {}
+
+ uuid@11.1.1: {}
+
+ vite@7.3.8:
+ dependencies:
+ esbuild: 0.28.2
+ fdir: 6.5.0(picomatch@4.0.7)
+ picomatch: 4.0.7
+ postcss: 8.5.33
+ rollup: 4.68.4
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ fsevents: 2.3.3
diff --git a/example-client/src/PowersyncConnector.singlefile.ts b/example-client/src/PowersyncConnector.singlefile.ts
index e9849c8..abb70df 100644
--- a/example-client/src/PowersyncConnector.singlefile.ts
+++ b/example-client/src/PowersyncConnector.singlefile.ts
@@ -1,36 +1,31 @@
// PowerSync Reference Write Implementation — single-file client connector
//
// Copy this file into your app to upload queued transactions with plain fetch.
-// It requires @powersync/web or @powersync/react-native >=1.26.0 for getCrudTransactions().
-// For the modular version, see PowersyncConnector.ts and library/powersync/.
+// It requires @powersync/web >=2.6.0 or @powersync/react-native >=2.4.0 for Authenticator and
+// MutationUploader. For the modular version, see PowersyncConnector.ts and library/powersync/.
//
-// Set BACKEND_URL, POWERSYNC_URL and AUTH_TOKEN below. Adjust the batch limits, request timeout,
-// and localStorage key as needed, or connect these constants to your application's configuration.
+// Set BACKEND_URL below. Adjust the batch limits, request timeout, and localStorage key as needed,
+// or connect these constants to your application's configuration.
//
-// The default fetchCredentials() uses the fixed AUTH_TOKEN for sync and reuses it for writes.
-// The write API accepts tokens your PowerSync instance trusts. Replace fetchAuthToken() with your
-// identity provider's token retrieval. Sync and writes should identify the same user.
+// Pass the connector's upload callback to connect(), together with your Authenticator:
+//
+// const connector = new PowersyncConnector({ authenticator });
+// await db.connect({ powerSyncEndpoint, authenticator, upload: connector.upload });
+//
+// Write requests use the authenticator's token. The write API accepts tokens your PowerSync
+// instance trusts. Sync and writes should identify the same user.
//
// Setup references:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#backend-connector
// See docs/auth/providers.md in this repository for Supabase and Clerk examples.
-import type { AbstractPowerSyncDatabase, CrudEntry, CrudTransaction, PowerSyncBackendConnector } from '@powersync/web';
+import type { Authenticator, CommonPowerSyncDatabase, CrudEntry, CrudTransaction, MutationUploader } from '@powersync/web';
// Configuration
/** Base URL of your write API, e.g. `http://localhost:6060` in local dev. */
const BACKEND_URL = 'http://localhost:6060';
-/** Your PowerSync instance URL. */
-const POWERSYNC_URL = '';
-
-/**
- * Token for sync and writes, e.g. a session token copied from your auth provider. Replace
- * fetchAuthToken() with your provider's token retrieval instead of hardcoding one.
- */
-const AUTH_TOKEN = '';
-
/** localStorage key used to persist the anonymous user id across reloads. */
const USER_ID_STORAGE_KEY = 'ps_user_id';
@@ -45,26 +40,22 @@ const REQUEST_TIMEOUT_MS = 30_000;
// Connector implementation; supporting types and helpers follow the class.
-export class PowersyncConnector implements PowerSyncBackendConnector {
+export class PowersyncConnector {
// Called by PowerSync to upload queued local changes to the write API.
- async uploadData(database: AbstractPowerSyncDatabase): Promise {
+ readonly upload: MutationUploader = ({ database }) => {
const batching = this.getBatchingConfig();
return this.uploadTransactionBatch(database, batching);
- }
-
- // Returns credentials for the PowerSync sync connection, reusing the write API token.
- // The write API accepts tokens your PowerSync instance trusts. See docs/auth/providers.md.
- async fetchCredentials() {
- return {
- endpoint: POWERSYNC_URL,
- token: await this.getAuthToken()
- };
- }
+ };
readonly userId: string;
- private _authToken: string | null;
+ private readonly authenticator: Authenticator;
- constructor() {
+ /**
+ * @param authenticator Supplies the bearer token for write API requests. Pass the authenticator you
+ * use for sync, or a separate one if writes need a different token. See docs/auth/providers.md.
+ */
+ constructor({ authenticator }: { authenticator: Authenticator }) {
+ this.authenticator = authenticator;
// Provide a crypto.randomUUID() polyfill or a platform UUID generator where unavailable,
// including older React Native environments.
let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
@@ -73,26 +64,6 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
localStorage.setItem(USER_ID_STORAGE_KEY, userId);
}
this.userId = userId;
- this._authToken = null;
- }
-
- // Replace with your auth provider's session token (e.g. Supabase `session.access_token`).
- private async fetchAuthToken(): Promise {
- if (!AUTH_TOKEN) {
- throw new Error('No auth token. Set AUTH_TOKEN or replace fetchAuthToken().');
- }
- return AUTH_TOKEN;
- }
-
- /**
- * Returns the cached token shared by sync and write requests.
- * Fetches a token on first use or after {@link onTransportError} clears the cache.
- */
- private async getAuthToken(): Promise {
- if (!this._authToken) {
- this._authToken = await this.fetchAuthToken();
- }
- return this._authToken;
}
/**
@@ -132,12 +103,13 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
/**
* Handles network errors, timeouts, and non-2xx responses through {@link onRetryableError}.
- * Clears the cached token on {@link AuthenticationError} so the next upload fetches a new one.
- * Override to handle transport failures separately from write API retryable results.
+ * On {@link AuthenticationError}, calls the authenticator's `invalidateCredentials()` so the next
+ * upload gets a new token. Override to handle transport failures separately from write API
+ * retryable results.
*/
protected async onTransportError(error: unknown): Promise {
if (error instanceof AuthenticationError) {
- this._authToken = null;
+ this.authenticator.invalidateCredentials?.();
}
const message = error instanceof Error ? error.message : String(error);
@@ -147,14 +119,14 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
/**
* POST /api/data via plain fetch — no openapi-fetch, no generated client. Every non-2xx response
* the write API returns (400/401/500) is `{ message }` (see backend/shared/powersync-reference-write-api.openapi.yaml); 401/403 become
- * an {@link AuthenticationError} so onTransportError can clear the cached token and retry.
+ * an {@link AuthenticationError} so onTransportError can invalidate the token and retry.
*/
private async postTransactionBatch(body: TransactionBatchAPI): Promise {
const response = await fetch(`${BACKEND_URL}/api/data`, {
method: 'POST',
headers: {
'content-type': 'application/json',
- Authorization: `Bearer ${await this.getAuthToken()}`
+ Authorization: `Bearer ${await this.authenticator.resolveCredentials({})}`
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
@@ -175,7 +147,7 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
}
private async uploadTransactionBatch(
- database: AbstractPowerSyncDatabase,
+ database: CommonPowerSyncDatabase,
batching: ReturnType
): Promise {
const batch: CrudTransaction[] = [];
diff --git a/example-client/src/PowersyncConnector.ts b/example-client/src/PowersyncConnector.ts
index 9a8fea0..f3a8d89 100644
--- a/example-client/src/PowersyncConnector.ts
+++ b/example-client/src/PowersyncConnector.ts
@@ -1,7 +1,7 @@
import { v4 as uuid } from 'uuid';
-// Requires @powersync/web or @powersync/react-native >=1.26.0 for getCrudTransactions().
-import type { AbstractPowerSyncDatabase, CrudTransaction, PowerSyncBackendConnector } from '@powersync/web';
+// Requires @powersync/web >=2.6.0 or @powersync/react-native >=2.4.0 for Authenticator and MutationUploader.
+import type { Authenticator, CommonPowerSyncDatabase, CrudTransaction, MutationUploader } from '@powersync/web';
import {
WriteAPIClient,
type TransactionResult,
@@ -17,31 +17,33 @@ import {
} from './library/powersync/DemoConnectorConfig';
import { completeAcceptedPrefix, sleep } from './library/powersync/TransactionBatching';
-export class PowersyncConnector implements PowerSyncBackendConnector {
+/**
+ * Uploads queued local changes to the write API. Pass {@link upload} to `connect()`:
+ *
+ * db.connect({ powerSyncEndpoint, authenticator, upload: new PowersyncConnector({ authenticator }).upload });
+ */
+export class PowersyncConnector {
// Called by PowerSync to upload queued local changes to the write API.
- async uploadData(database: AbstractPowerSyncDatabase): Promise {
+ readonly upload: MutationUploader = ({ database }) => {
const batching = this.getBatchingConfig();
return this.uploadTransactionBatch(database, batching);
- }
-
- // Returns credentials for the PowerSync sync connection, reusing the write API token.
- // The write API accepts tokens your PowerSync instance trusts. See docs/auth/providers.md.
- async fetchCredentials() {
- return {
- endpoint: this.config.powersyncUrl,
- token: await this.getAuthToken()
- };
- }
+ };
readonly config: DemoConfig;
readonly userId: string;
readonly apiClient: OpenAPIClient;
+ private readonly authenticator: Authenticator;
private _clientId: string | null;
private _writeClient: WriteAPIClient | null;
- private _authToken: string | null;
- constructor() {
+ /**
+ * @param authenticator Supplies the bearer token for write API requests. Pass the authenticator you
+ * use for sync, or a separate one if writes need a different token. The write API accepts tokens
+ * your PowerSync instance trusts. See docs/auth/providers.md.
+ */
+ constructor({ authenticator }: { authenticator: Authenticator }) {
+ this.authenticator = authenticator;
let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
if (!userId) {
userId = uuid();
@@ -50,36 +52,15 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
this.userId = userId;
this._clientId = null;
this._writeClient = null;
- this._authToken = null;
this.config = readDemoConfig();
this.apiClient = createOpenAPIClient(this.config.backendUrl, {
timeoutMs: this.config.requestTimeoutMs,
- getAuthToken: () => this.getAuthToken()
+ getAuthToken: () => this.authenticator.resolveCredentials({})
});
}
- // Replace with your auth provider's session token (e.g. Supabase `session.access_token`).
- // The demo reads a fixed token from VITE_POWERSYNC_TOKEN.
- private async fetchAuthToken(): Promise {
- if (!this.config.authToken) {
- throw new Error('No auth token. Set VITE_POWERSYNC_TOKEN or replace fetchAuthToken().');
- }
- return this.config.authToken;
- }
-
- /**
- * Returns the cached token shared by sync and write requests.
- * Fetches a token on first use or after {@link onTransportError} clears the cache.
- */
- private async getAuthToken(): Promise {
- if (!this._authToken) {
- this._authToken = await this.fetchAuthToken();
- }
- return this._authToken;
- }
-
/**
* The batching config to use for the current upload. Reads the env-derived default; override to
* make batching dynamic (e.g. shrink batch size after a fatal error, adjust for network conditions).
@@ -88,7 +69,7 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
return this.config.batching || DEFAULT_BATCHING_CONFIG;
}
- private async getWriteClient(database: AbstractPowerSyncDatabase): Promise {
+ private async getWriteClient(database: CommonPowerSyncDatabase): Promise {
if (!this._writeClient) {
this._writeClient = new WriteAPIClient({
transport: this.apiClient.transport,
@@ -124,19 +105,20 @@ export class PowersyncConnector implements PowerSyncBackendConnector {
/**
* Handles network errors, timeouts, and non-2xx responses through {@link onRetryableError}.
- * Clears the cached token on {@link AuthenticationError} so the next upload fetches a new one.
- * Override to handle transport failures separately from write API retryable results.
+ * On {@link AuthenticationError}, calls the authenticator's `invalidateCredentials()` so the next
+ * upload gets a new token. Override to handle transport failures separately from write API
+ * retryable results.
*/
protected async onTransportError(error: unknown): Promise {
if (error instanceof AuthenticationError) {
- this._authToken = null;
+ this.authenticator.invalidateCredentials?.();
}
const message = error instanceof Error ? error.message : String(error);
return this.onRetryableError({ status: 'retryable_error', message });
}
- private async uploadTransactionBatch(database: AbstractPowerSyncDatabase, batching: BatchingConfig): Promise {
+ private async uploadTransactionBatch(database: CommonPowerSyncDatabase, batching: BatchingConfig): Promise {
const batch: CrudTransaction[] = [];
let operations = 0;
diff --git a/example-client/tsconfig.json b/example-client/tsconfig.json
new file mode 100644
index 0000000..5ec27e4
--- /dev/null
+++ b/example-client/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "types": ["vite/client"],
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "isolatedModules": true
+ },
+ "include": ["src"]
+}