Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions configuration/app-backend/backend-connector-examples.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ keywords:
- "backend connector"
- "uploadData"
- "fetchCredentials"
- "Authenticator"
- "MutationUploader"
- "connector snippet"
---

Expand All @@ -26,7 +28,7 @@ import SupabaseDotnet from '/snippets/backend-connectors/supabase/dotnet.mdx';

{/* Other projects, such as the PowerSync Dashboard, show these snippets. Keep the instance URL placeholder unchanged: those projects replace it with the instance URL. */}

Each example implements the two methods of a [backend connector](/configuration/app-backend/client-side-integration#backend-connector): `fetchCredentials()` and `uploadData()`. The Rust SDK splits these into an `Authenticator` and a `MutationUploader`. Copy the example for your SDK into your app, then replace the placeholders.
Each example implements authentication and uploads separately: an `Authenticator` supplies the token, and a mutation uploader uploads queued writes. Each `Authenticator` caches its token and clears the cache in `invalidateCredentials()`, because the SDK isn't guaranteed to cache tokens. The .NET examples implement the two methods of a [backend connector](/configuration/app-backend/client-side-integration#backend-connector) instead, `fetchCredentials()` and `uploadData()`, because no stable .NET SDK release supports the split API yet. Copy the example for your SDK into your app, then replace the placeholders.

<CardGroup cols={2}>
<Card title="Custom Backend" icon="server" href="#custom-backend">
Expand All @@ -40,7 +42,7 @@ Each example implements the two methods of a [backend connector](/configuration/

## Custom Backend

Use these examples if your app uploads writes to its own backend. By default, they call the [reference write API](/handling-writes/write-path/reference-write-implementation)'s `POST /api/data`. If your API's request or response format differs, either change the request and response handling in `uploadData()` to match your API, or use the [prompt for your coding agent](/handling-writes/write-path/existing-api#prompt-for-your-coding-agent) to generate an `uploadData()` for it.
Use these examples if your app uploads writes to its own backend. By default, they call the [reference write API](/handling-writes/write-path/reference-write-implementation)'s `POST /api/data`. If your API's request or response format differs, either change the example's request and response handling to match your API, or use the [prompt for your coding agent](/handling-writes/write-path/existing-api#prompt-for-your-coding-agent) to generate upload code for it.

Each example sends the same JWT to your PowerSync instance and to the write API. Replace the token placeholder with a token from your auth provider. See [Authentication Setup](/configuration/auth/overview).

Expand Down
42 changes: 28 additions & 14 deletions handling-writes/write-path/reference-write-implementation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: "Run PowerSync's open-source write API against your source database
If you don't have a write API yet, you can run the reference write implementation instead of building one. It has two parts:

- The **reference write API**: a Node.js (Express) server that receives uploaded transactions and applies them to your source database. It supports Postgres, MongoDB, MySQL, and SQL Server.
- The **reference connector**: a TypeScript backend connector with an `uploadData()` that calls the reference write API. You copy it into your app. For other SDKs, the [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) port its upload behavior.
- The **reference connector**: a TypeScript mutation uploader that uploads queued transactions to the reference write API. You copy it into your app. For other SDKs, the [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) port its upload behavior.

An [OpenAPI spec](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-api.openapi.yaml) defines the API between the two parts. If your backend runs on another stack, see [Build Your Own Write API](/handling-writes/write-path/build-your-own-write-api).

Expand Down Expand Up @@ -76,35 +76,49 @@ If your source database is Supabase and you rely on RLS policies to authorize wr
<Step title="Connect Your App">
<span id="connect-your-app" />

Copy the reference connector from the repository's [`example-client`](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main/example-client) folder into your app. If your app already has a `fetchCredentials()`, keep it, and copy only `uploadData()` and the code it uses.
Copy the reference connector from the repository's [`example-client`](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main/example-client) folder into your app. It requires `@powersync/web` 2.6.0 or `@powersync/react-native` 2.4.0 or later.

If your app uses the Dart, Kotlin, Swift, .NET, or Rust SDK, copy the Custom Backend example for your SDK from [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) instead, and skip the rest of this step. Each example sends one transaction per request and leaves retry timing to the SDK.

There are two versions of the connector:

- [**Single file**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts): copy `src/PowersyncConnector.singlefile.ts`. It requires only your PowerSync SDK. Set the write API URL, the PowerSync instance URL, and the batch size in the constants at the top of the file.
- [**Single file**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts): copy `src/PowersyncConnector.singlefile.ts`. It requires only your PowerSync SDK. Set the write API URL and the batch size in the constants at the top of the file.
- [**Modular**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.ts): copy `src/PowersyncConnector.ts`, `src/library/powersync/`, and `src/generated/api.d.ts`, preserving their relative paths. Install `openapi-fetch` and `uuid` alongside your PowerSync SDK. This version reads the same settings from `VITE_` environment variables.

Use a write API URL that the device can reach: `localhost` on a phone refers to the phone.

Replace the demo `fetchAuthToken()` with code that retrieves the current token from your auth provider. If the provider SDK manages session refresh, remove the `_authToken` field, its initialization in the constructor, and the `AuthenticationError` check in `onTransportError()` that resets it. Then replace `getAuthToken()` with:
The connector gets the token for write requests from an `Authenticator`. Pass it the same `Authenticator` that you pass to `connect()` for sync, so that sync and writes identify the same user. When the write API rejects the token, the connector calls `invalidateCredentials()` and keeps the transaction in the upload queue, so the next attempt uses a new token.

```typescript
// Inside your copied PowersyncConnector class.
private async getAuthToken(): Promise<string> {
return this.fetchAuthToken();
}
```

The demo cache is cleared only after an upload request fails authentication. Keeping it can make `fetchCredentials()` return an expired token even after the provider refreshes the session. See [client authentication](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#authentication) for provider integration.
The SDK isn't guaranteed to cache tokens from an `Authenticator`, so cache the token in `resolveCredentials()` and clear the cache in `invalidateCredentials()`. Do this even if your auth provider's SDK refreshes sessions itself: after the cache is cleared, the next call gets the provider's current token. See [client authentication](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#authentication) for provider examples.

Pass the connector to your PowerSync database, adjusting the import path to match your copied file:
Connect your PowerSync database with the `Authenticator` and the connector's `upload` callback, adjusting the import path to match your copied file:

```typescript
import type { Authenticator } from '@powersync/web';
import { PowersyncConnector } from './PowersyncConnector';

await db.connect(new PowersyncConnector());
let cachedToken: string | null = null;

const authenticator: Authenticator = {
async resolveCredentials() {
// fetchAuthToken() is your code that gets a token from your auth provider.
cachedToken ??= await fetchAuthToken();
return cachedToken;
},
invalidateCredentials() {
cachedToken = null;
}
};

const connector = new PowersyncConnector({ authenticator });
await db.connect({
powerSyncEndpoint: 'https://<instance-id>.powersync.journeyapps.com',
authenticator,
upload: connector.upload
});
```

If your app already connects with a `PowerSyncBackendConnector`, see [Migrating from a Backend Connector](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#migrating-from-a-backend-connector).
</Step>
<Step title="Add Authorization">
Add your checks to the `authorize()` function in `backend/standalone/src/auth/authorizer.ts`. It receives the transaction's operations and the verified token's `sub` and claims, and returns `false` to reject the transaction. By default, it allows every write and logs an error for each transaction until you replace it. See the repository's [authorization guide](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/authorization.md).
Expand Down
50 changes: 26 additions & 24 deletions handling-writes/write-path/supabase-edge-function.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -78,37 +78,39 @@ The function runs each write as the signed-in user. Inside each transaction, it
Copy the reference connector into your app, as described in the reference write implementation's [Connect Your App step](/handling-writes/write-path/reference-write-implementation#connect-your-app). Then make these changes:

1. Set the connector's write API URL to `https://<project-ref>.supabase.co/functions/v1/powersync-write`. Your PowerSync instance URL doesn't change.
2. Pass your app's supabase-js client to the connector, and replace `fetchCredentials()` and `getAuthToken()` with the code below. This code reads the session on every call.
3. Remove `fetchAuthToken()`, the `_authToken` field, its initialization in the constructor, and the `AuthenticationError` check in `onTransportError()` that resets it. supabase-js refreshes the session itself. The connector clears its cache only after a write request fails authentication, so while the cache is in place, sync keeps sending an expired token.
2. Use an `Authenticator` that reads the access token from your app's supabase-js client, and pass it to both `connect()` and the connector. Cache the token and clear the cache in `invalidateCredentials()`, as in the code below. The SDK 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.

```typescript
constructor(private readonly supabase: SupabaseClient) {
// existing setup
}
import type { SupabaseClient } from '@supabase/supabase-js';
import type { Authenticator } from '@powersync/web';
import { PowersyncConnector } from './PowersyncConnector';

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
};
}
declare const supabase: SupabaseClient; // Your app's supabase-js client

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;
}
let cachedToken: string | null = null;

// Write requests call this to get their token.
private async getAuthToken(): Promise<string> {
return (await this.getSession()).access_token;
}
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: 'https://<instance-id>.powersync.journeyapps.com',
authenticator,
upload: connector.upload
});
```

This code is for the modular connector. In the single-file connector, use `POWERSYNC_URL` instead of `this.config.powersyncUrl`.

The function accepts only a signed-in user's access token. It rejects API keys, anon tokens, and service-role tokens.
</Step>
</Steps>
Expand Down
Loading
Loading