connect() function. The uploader’s connect() passes both parts, so use it in place of the authenticator’s. Start with the authenticator, and add the uploader before your app writes data.
Each authenticator caches its token and clears the cache in invalidateCredentials(), so that resolveCredentials() stays cheap and returns a new token after the SDK invalidates the old one. If your auth library already stores and refreshes the token, you can return that token instead. See When resolveCredentials() is Called. The Kotlin Supabase example does this: it uses the SupabaseAuthenticator and SupabaseUploader classes from the Kotlin SDK’s Supabase integration, and SupabaseAuthenticator reads the token from the Supabase client’s current session on each call.
Copy the files for your SDK into your app, then replace the placeholders.
Custom Backend
Your app uses your own auth provider and uploads writes to your own backend, or to the reference write endpoint.
Supabase
Your source database is Supabase and your app uses Supabase Auth.
Custom Backend
The authenticator returns a placeholder token. Replace it with a token from your auth provider. See Authentication Setup. The uploader calls the reference write endpoint,POST /api/data, and sends it the authenticator’s token. The write endpoint accepts the same JWTs as your PowerSync instance. If your API’s request or response format differs, either change the uploader’s request and response handling to match your API, or use the prompt for your coding agent to generate an uploader for it.
- JavaScript
- TypeScript
- React Native
- Dart
- Kotlin
- Swift
- .NET
- Rust
1
Connect for Downloads
PowerSyncAuthenticator.js
// Requires @powersync/web 2.6.0 or later.
/**
* Connects `db` to your PowerSync instance with this authenticator.
*/
export async function connect(db) {
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator: new MyAuthenticator()
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
});
}
/**
* Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
* expire or is rejected.
*/
export class MyAuthenticator {
constructor() {
this.token = null;
}
async resolveCredentials() {
if (!this.token) {
this.token = await this.fetchAuthToken();
}
return this.token;
}
/**
* The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
* resolveCredentials() call must return a new token. This cache suits a token that you request from your backend. If
* fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you can
* return that token without this cache and ask the library to refresh it here instead. See
* https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
*/
invalidateCredentials() {
this.token = null;
}
/**
* Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
* Supabase and Firebase tokens can be used as they are:
* - https://docs.powersync.com/configuration/auth/supabase-auth
* - https://docs.powersync.com/configuration/auth/firebase-auth
* To get started without an auth provider, use a development token:
* https://docs.powersync.com/configuration/auth/development-tokens
*/
async fetchAuthToken() {
return 'An authentication token';
}
}
2
Add Uploads
PowerSyncUploader.js
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires @powersync/web 2.6.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in postTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
// The authenticator from your read setup.
import { MyAuthenticator } from './PowerSyncAuthenticator';
// Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself.
const BACKEND_URL = 'http://localhost:6060';
// Abort a write endpoint request after this many milliseconds.
const REQUEST_TIMEOUT_MS = 30000;
/**
* Connects `db` with the authenticator and this uploader. Use this instead of the connect() in your
* authenticator file, and delete that one.
*/
export async function connect(db) {
const authenticator = new MyAuthenticator();
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator,
upload: new MyMutationUploader({ authenticator }).upload
});
}
export class MyMutationUploader {
/**
* @param authenticator Supplies the token for write endpoint requests. The write endpoint accepts the same JWTs
* as your PowerSync instance, so this is the same authenticator that you connect with.
*/
constructor({ authenticator }) {
this.authenticator = authenticator;
// connect() passes upload() to the SDK on its own, so bind it to this uploader.
this.upload = this.upload.bind(this);
}
/**
* Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
* keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
* and the SDK retries after a delay.
* See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
*/
async upload({ database }) {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let result;
try {
result = await this.postTransaction(transaction);
} catch (error) {
// Network errors, timeouts and non-2xx responses.
if (error instanceof AuthenticationError && this.authenticator.invalidateCredentials) {
this.authenticator.invalidateCredentials(); // Fetch a new token before the next attempt.
}
throw error;
}
if (result.status === 'retryable_error') {
throw new Error(result.message || 'Retryable error');
}
if (result.status === 'not_attempted') {
throw new Error('Write endpoint did not attempt the transaction');
}
if (result.status === 'fatal_error' && result.requires_client_handling) {
if ((await this.onFatalTransaction(transaction, result)) === 'retain') {
throw new Error('Transaction retained after ' + result.failed_operation.error_code);
}
}
// Success, a fatal error that the write endpoint already handled (for example, with a dead-letter hook),
// or a fatal error that onFatalTransaction() chose to discard.
await transaction.complete();
}
/**
* Called for fatal errors that the write endpoint leaves to the client. 'retain' keeps the transaction queued,
* which blocks later uploads, and the SDK calls this again on its next attempt. Return 'complete' to discard
* the transaction, for example after telling the user.
* See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
*/
async onFatalTransaction(transaction, result) {
console.error('Transaction needs client handling:', result.failed_operation.error_code, result.message);
return 'retain';
}
/**
* Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined
* by the write endpoint's OpenAPI spec:
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
*/
async postTransaction(transaction) {
const body = {
transactions: [
{
transaction_id: transaction.transactionId,
crud: transaction.crud.map((op) => ({
id: op.id,
op: op.op, // 'PUT', 'PATCH' or 'DELETE'
table: op.table,
transaction_id: op.transactionId,
op_data: op.opData // Changed columns for PUT and PATCH, undefined for DELETE
}))
}
]
};
const response = await fetch(BACKEND_URL + '/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + (await this.authenticator.resolveCredentials({}))
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
if (!response.ok) {
// Every non-2xx response from the write endpoint has the shape { message }.
const { message } = await response.json().catch(() => ({ message: response.statusText }));
if (response.status === 401 || response.status === 403) {
throw new AuthenticationError('Write endpoint rejected the token (' + response.status + '): ' + message);
}
throw new Error('Write endpoint request failed (' + response.status + '): ' + message);
}
// One result per transaction sent. A result's status is 'success', 'retryable_error', 'fatal_error' or
// 'not_attempted'. A fatal error has requires_client_handling and failed_operation.error_code.
const { results } = await response.json();
if (!Array.isArray(results) || results.length !== 1) {
throw new Error('Expected one result for one transaction');
}
return results[0];
}
}
// Thrown when the write endpoint rejects the token (401 or 403).
class AuthenticationError extends Error {}
1
Connect for Downloads
PowerSyncAuthenticator.ts
// Requires @powersync/web 2.6.0 or later.
import type { Authenticator, CommonPowerSyncDatabase } from '@powersync/web';
/**
* Connects `db` to your PowerSync instance with this authenticator.
*/
export async function connect(db: CommonPowerSyncDatabase) {
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator: new MyAuthenticator()
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
});
}
/**
* Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
* expire or is rejected.
*/
export class MyAuthenticator implements Authenticator {
private token: string | null = null;
async resolveCredentials(): Promise<string> {
this.token ??= await this.fetchAuthToken();
return this.token;
}
/**
* The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
* resolveCredentials() call must return a new token. This cache suits a token that you request from your backend. If
* fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you can
* return that token without this cache and ask the library to refresh it here instead. See
* https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
*/
invalidateCredentials(): void {
this.token = null;
}
/**
* Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
* Supabase and Firebase tokens can be used as they are:
* - https://docs.powersync.com/configuration/auth/supabase-auth
* - https://docs.powersync.com/configuration/auth/firebase-auth
* To get started without an auth provider, use a development token:
* https://docs.powersync.com/configuration/auth/development-tokens
*/
private async fetchAuthToken(): Promise<string> {
return 'An authentication token';
}
}
2
Add Uploads
PowerSyncUploader.ts
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires @powersync/web 2.6.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in postTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
import type { Authenticator, CommonPowerSyncDatabase, CrudTransaction, MutationUploader } from '@powersync/web';
// The authenticator from your read setup.
import { MyAuthenticator } from './PowerSyncAuthenticator';
/** Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself. */
const BACKEND_URL = 'http://localhost:6060';
/** Abort a write endpoint request after this many milliseconds. */
const REQUEST_TIMEOUT_MS = 30_000;
/**
* Connects `db` with the authenticator and this uploader. Use this instead of the connect() in your
* authenticator file, and delete that one.
*/
export async function connect(db: CommonPowerSyncDatabase) {
const authenticator = new MyAuthenticator();
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator,
upload: new MyMutationUploader({ authenticator }).upload
});
}
export class MyMutationUploader {
private readonly authenticator: Authenticator;
/**
* @param authenticator Supplies the token for write endpoint requests. The write endpoint accepts the same JWTs
* as your PowerSync instance, so this is the same authenticator that you connect with.
*/
constructor({ authenticator }: { authenticator: Authenticator }) {
this.authenticator = authenticator;
}
/**
* Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
* keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
* and the SDK retries after a delay.
* See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
*/
readonly upload: MutationUploader = async ({ database }) => {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let result: TransactionResult;
try {
result = await this.postTransaction(transaction);
} catch (error) {
// Network errors, timeouts and non-2xx responses.
if (error instanceof AuthenticationError) {
this.authenticator.invalidateCredentials?.(); // Fetch a new token before the next attempt.
}
throw error;
}
if (result.status === 'retryable_error') {
throw new Error(result.message ?? 'Retryable error');
}
if (result.status === 'not_attempted') {
throw new Error('Write endpoint did not attempt the transaction');
}
if (result.status === 'fatal_error' && result.requires_client_handling) {
if ((await this.onFatalTransaction(transaction, result)) === 'retain') {
throw new Error(`Transaction retained after ${result.failed_operation.error_code}`);
}
}
// Success, a fatal error that the write endpoint already handled (for example, with a dead-letter hook),
// or a fatal error that onFatalTransaction() chose to discard.
await transaction.complete();
};
/**
* Called for fatal errors that the write endpoint leaves to the client. 'retain' keeps the transaction queued,
* which blocks later uploads, and the SDK calls this again on its next attempt. Return 'complete' to discard
* the transaction, for example after telling the user.
* See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
*/
protected async onFatalTransaction(
transaction: CrudTransaction,
result: FatalResult
): Promise<'retain' | 'complete'> {
console.error('Transaction needs client handling:', result.failed_operation.error_code, result.message);
return 'retain';
}
/** Sends one transaction to POST /api/data and returns its result. */
private async postTransaction(transaction: CrudTransaction): Promise<TransactionResult> {
const body = {
transactions: [
{
transaction_id: transaction.transactionId,
crud: transaction.crud.map((op) => ({
id: op.id,
op: op.op, // 'PUT', 'PATCH' or 'DELETE'
table: op.table,
transaction_id: op.transactionId,
op_data: op.opData // Changed columns for PUT and PATCH, undefined for DELETE
}))
}
]
};
const response = await fetch(`${BACKEND_URL}/api/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${await this.authenticator.resolveCredentials({})}`
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
if (!response.ok) {
// Every non-2xx response from the write endpoint has the shape { message }.
const { message } = await response.json().catch(() => ({ message: response.statusText }));
if (response.status === 401 || response.status === 403) {
throw new AuthenticationError(`Write endpoint rejected the token (${response.status}): ${message}`);
}
throw new Error(`Write endpoint request failed (${response.status}): ${message}`);
}
const { results } = (await response.json()) as { results: TransactionResult[] };
if (!Array.isArray(results) || results.length !== 1) {
throw new Error('Expected one result for one transaction');
}
return results[0];
}
}
// Response types from the write endpoint's OpenAPI spec:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
interface FatalResult {
status: 'fatal_error';
message?: string;
/** True: the write endpoint leaves the decision to the client. False: the write endpoint already handled the failure. */
requires_client_handling: boolean;
failed_operation: {
/** For example 'UNIQUE_VIOLATION', 'INVALID_DATA', 'UNAUTHORIZED', or an application-defined code. */
error_code: string;
message?: string;
details?: unknown;
operation_index?: number;
};
}
type TransactionResult =
| { status: 'success' | 'not_attempted' }
| { status: 'retryable_error'; message?: string; retry_after_ms?: number }
| FatalResult;
/** Thrown when the write endpoint rejects the token (401 or 403). */
class AuthenticationError extends Error {}
1
Connect for Downloads
PowerSyncAuthenticator.ts
// Requires @powersync/react-native 2.4.0 or later.
import type { Authenticator, CommonPowerSyncDatabase } from '@powersync/react-native';
/**
* Connects `db` to your PowerSync instance with this authenticator.
*/
export async function connect(db: CommonPowerSyncDatabase) {
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator: new MyAuthenticator()
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
});
}
/**
* Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
* expire or is rejected.
*/
export class MyAuthenticator implements Authenticator {
private token: string | null = null;
async resolveCredentials(): Promise<string> {
this.token ??= await this.fetchAuthToken();
return this.token;
}
/**
* The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
* resolveCredentials() call must return a new token. This cache suits a token that you request from your backend. If
* fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you can
* return that token without this cache and ask the library to refresh it here instead. See
* https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
*/
invalidateCredentials(): void {
this.token = null;
}
/**
* Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
* Supabase and Firebase tokens can be used as they are:
* - https://docs.powersync.com/configuration/auth/supabase-auth
* - https://docs.powersync.com/configuration/auth/firebase-auth
* To get started without an auth provider, use a development token:
* https://docs.powersync.com/configuration/auth/development-tokens
*/
private async fetchAuthToken(): Promise<string> {
return 'An authentication token';
}
}
2
Add Uploads
PowerSyncUploader.ts
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires @powersync/react-native 2.4.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in postTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
import type { Authenticator, CommonPowerSyncDatabase, CrudTransaction, MutationUploader } from '@powersync/react-native';
// The authenticator from your read setup.
import { MyAuthenticator } from './PowerSyncAuthenticator';
/** Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself. */
const BACKEND_URL = 'http://localhost:6060';
/** Abort a write endpoint request after this many milliseconds. */
const REQUEST_TIMEOUT_MS = 30_000;
/**
* Connects `db` with the authenticator and this uploader. Use this instead of the connect() in your
* authenticator file, and delete that one.
*/
export async function connect(db: CommonPowerSyncDatabase) {
const authenticator = new MyAuthenticator();
await db.connect({
powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator,
upload: new MyMutationUploader({ authenticator }).upload
});
}
export class MyMutationUploader {
private readonly authenticator: Authenticator;
/**
* @param authenticator Supplies the token for write endpoint requests. The write endpoint accepts the same JWTs
* as your PowerSync instance, so this is the same authenticator that you connect with.
*/
constructor({ authenticator }: { authenticator: Authenticator }) {
this.authenticator = authenticator;
}
/**
* Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
* keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
* and the SDK retries after a delay.
* See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
*/
readonly upload: MutationUploader = async ({ database }) => {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let result: TransactionResult;
try {
result = await this.postTransaction(transaction);
} catch (error) {
// Network errors, timeouts and non-2xx responses.
if (error instanceof AuthenticationError) {
this.authenticator.invalidateCredentials?.(); // Fetch a new token before the next attempt.
}
throw error;
}
if (result.status === 'retryable_error') {
throw new Error(result.message ?? 'Retryable error');
}
if (result.status === 'not_attempted') {
throw new Error('Write endpoint did not attempt the transaction');
}
if (result.status === 'fatal_error' && result.requires_client_handling) {
if ((await this.onFatalTransaction(transaction, result)) === 'retain') {
throw new Error(`Transaction retained after ${result.failed_operation.error_code}`);
}
}
// Success, a fatal error that the write endpoint already handled (for example, with a dead-letter hook),
// or a fatal error that onFatalTransaction() chose to discard.
await transaction.complete();
};
/**
* Called for fatal errors that the write endpoint leaves to the client. 'retain' keeps the transaction queued,
* which blocks later uploads, and the SDK calls this again on its next attempt. Return 'complete' to discard
* the transaction, for example after telling the user.
* See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
*/
protected async onFatalTransaction(
transaction: CrudTransaction,
result: FatalResult
): Promise<'retain' | 'complete'> {
console.error('Transaction needs client handling:', result.failed_operation.error_code, result.message);
return 'retain';
}
/** Sends one transaction to POST /api/data and returns its result. */
private async postTransaction(transaction: CrudTransaction): Promise<TransactionResult> {
const body = {
transactions: [
{
transaction_id: transaction.transactionId,
crud: transaction.crud.map((op) => ({
id: op.id,
op: op.op, // 'PUT', 'PATCH' or 'DELETE'
table: op.table,
transaction_id: op.transactionId,
op_data: op.opData // Changed columns for PUT and PATCH, undefined for DELETE
}))
}
]
};
// Older React Native versions and React Native's type definitions lack AbortSignal.timeout(), so use a timer.
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let response: Response;
try {
response = await fetch(`${BACKEND_URL}/api/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${await this.authenticator.resolveCredentials({})}`
},
body: JSON.stringify(body),
signal: controller.signal
});
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
// Every non-2xx response from the write endpoint has the shape { message }.
const { message } = await response.json().catch(() => ({ message: response.statusText }));
if (response.status === 401 || response.status === 403) {
throw new AuthenticationError(`Write endpoint rejected the token (${response.status}): ${message}`);
}
throw new Error(`Write endpoint request failed (${response.status}): ${message}`);
}
const { results } = (await response.json()) as { results: TransactionResult[] };
if (!Array.isArray(results) || results.length !== 1) {
throw new Error('Expected one result for one transaction');
}
return results[0];
}
}
// Response types from the write endpoint's OpenAPI spec:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
interface FatalResult {
status: 'fatal_error';
message?: string;
/** True: the write endpoint leaves the decision to the client. False: the write endpoint already handled the failure. */
requires_client_handling: boolean;
failed_operation: {
/** For example 'UNIQUE_VIOLATION', 'INVALID_DATA', 'UNAUTHORIZED', or an application-defined code. */
error_code: string;
message?: string;
details?: unknown;
operation_index?: number;
};
}
type TransactionResult =
| { status: 'success' | 'not_attempted' }
| { status: 'retryable_error'; message?: string; retry_after_ms?: number }
| FatalResult;
/** Thrown when the write endpoint rejects the token (401 or 403). */
class AuthenticationError extends Error {}
1
Connect for Downloads
lib/powersync_authenticator.dart
// Requires powersync 2.6.0 or later.
import 'package:powersync/powersync.dart';
/// Connects [db] to your PowerSync instance with this authenticator.
Future<void> connect(PowerSyncDatabase db) async {
await db.connect(
// To upload local writes, use ConnectRequest(...) and also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
connector: ConnectRequest.downloadOnly(
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator: MyAuthenticator(),
),
);
}
/// Provides the token that the SDK sends to your PowerSync instance. The token is cached until it expires or is
/// rejected.
class MyAuthenticator implements Authenticator {
String? _token;
@override
Future<String> resolveCredentials(Future<void> abortSignal) async {
return _token ??= await _fetchAuthToken();
}
/// The SDK calls this when the token expires and when the PowerSync Service rejects it, and the next
/// resolveCredentials() call must return a new token. This cache suits a token that you request from your backend. If
/// _fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you can
/// return that token without this cache and ask the library to refresh it here instead. See
/// https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
@override
void invalidateCredentials() {
_token = null;
}
/// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
/// Supabase and Firebase tokens can be used as they are:
/// - https://docs.powersync.com/configuration/auth/supabase-auth
/// - https://docs.powersync.com/configuration/auth/firebase-auth
/// To get started without an auth provider, use a development token:
/// https://docs.powersync.com/configuration/auth/development-tokens
Future<String> _fetchAuthToken() async {
return 'An authentication token';
}
}
2
Add Uploads
lib/powersync_uploader.dart
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires powersync 2.6.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in _postTransaction() to match
// it, or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http; // Add the http package: https://pub.dev/packages/http
import 'package:powersync/powersync.dart';
// The authenticator from your read setup.
import 'powersync_authenticator.dart';
/// Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself.
const backendUrl = 'http://localhost:6060';
/// Abort a write endpoint request after this long.
const requestTimeout = Duration(seconds: 30);
/// Connects [db] with the authenticator and this uploader. Use this instead of the connect() in your
/// authenticator file, and delete that one.
Future<void> connect(PowerSyncDatabase db) async {
final authenticator = MyAuthenticator();
await db.connect(
connector: ConnectRequest(
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
authenticator: authenticator,
uploader: MyMutationUploader(authenticator),
),
);
}
class MyMutationUploader implements MutationUploader {
/// Takes the authenticator that supplies the token for write endpoint requests. The write endpoint accepts the
/// same JWTs as your PowerSync instance, so this is the same authenticator that you connect with.
MyMutationUploader(this._authenticator);
final Authenticator _authenticator;
/// Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
/// keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
/// and the SDK retries after a delay.
/// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
@override
Future<void> upload(PowerSyncDatabase database, Future<void> abortSignal) async {
final transaction = await database.getNextCrudTransaction();
if (transaction == null) {
return;
}
final Map<String, dynamic> result;
try {
result = await _postTransaction(transaction);
} on AuthenticationException {
// Fetch a new token before the next attempt.
_authenticator.invalidateCredentials();
rethrow;
}
switch (result['status']) {
case 'success':
break;
case 'retryable_error':
throw Exception(result['message'] ?? 'Retryable error');
case 'fatal_error':
if (result['requires_client_handling'] == true &&
await onFatalTransaction(transaction, result) == FatalDecision.retain) {
throw Exception('Transaction retained after ${result['failed_operation']['error_code']}');
}
// A fatal error that the write endpoint already handled (for example, with a dead-letter hook), or one that
// onFatalTransaction() chose to discard.
break;
default:
throw Exception('Unexpected transaction result: ${result['status']}');
}
await transaction.complete();
}
/// Called for fatal errors that the write endpoint leaves to the client. [FatalDecision.retain] keeps the
/// transaction queued, which blocks later uploads, and the SDK calls this again on its next attempt. Return
/// [FatalDecision.complete] to discard the transaction, for example after telling the user.
/// See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
Future<FatalDecision> onFatalTransaction(CrudTransaction transaction, Map<String, dynamic> result) async {
print('Transaction needs client handling: ${result['failed_operation']['error_code']} ${result['message']}');
return FatalDecision.retain;
}
/// Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined
/// by the write endpoint's OpenAPI spec:
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
Future<Map<String, dynamic>> _postTransaction(CrudTransaction transaction) async {
final body = {
'transactions': [
{
if (transaction.transactionId != null) 'transaction_id': transaction.transactionId,
'crud': [
for (final op in transaction.crud)
{
'id': op.id,
'op': op.op.json, // PUT, PATCH or DELETE
'table': op.table,
if (op.transactionId != null) 'transaction_id': op.transactionId,
if (op.opData != null) 'op_data': op.opData, // Changed columns for PUT and PATCH
},
],
},
],
};
final response = await http
.post(
Uri.parse('$backendUrl/api/data'),
headers: {
'Content-Type': 'application/json',
// The abort signal is a future that never completes, so the request for a token is never aborted.
'Authorization': 'Bearer ${await _authenticator.resolveCredentials(Completer<void>().future)}',
},
body: jsonEncode(body),
)
.timeout(requestTimeout);
if (response.statusCode < 200 || response.statusCode >= 300) {
// Every non-2xx response from the write endpoint has the shape { message }.
String message;
try {
message = jsonDecode(response.body)['message'] as String;
} catch (_) {
message = response.reasonPhrase ?? '';
}
if (response.statusCode == 401 || response.statusCode == 403) {
throw AuthenticationException('Write endpoint rejected the token (${response.statusCode}): $message');
}
throw Exception('Write endpoint request failed (${response.statusCode}): $message');
}
// One result per transaction sent. A result's status is 'success', 'retryable_error', 'fatal_error' or
// 'not_attempted'. A fatal error has requires_client_handling and failed_operation.error_code.
final results = jsonDecode(response.body)['results'];
if (results is! List || results.length != 1) {
throw Exception('Expected one result for one transaction');
}
return Map<String, dynamic>.from(results.first as Map);
}
}
enum FatalDecision { retain, complete }
/// Thrown when the write endpoint rejects the token (401 or 403).
class AuthenticationException implements Exception {
AuthenticationException(this.message);
final String message;
@override
String toString() => message;
}
1
Connect for Downloads
PowerSyncAuthenticator.kt
// Requires PowerSync Kotlin SDK 1.16.0 or later.
import com.powersync.PowerSyncDatabase
import com.powersync.connectors.Authenticator
/**
* Connects `db` to your PowerSync instance with this authenticator.
*/
suspend fun connect(db: PowerSyncDatabase) {
db.connect(
endpoint = "[Your PowerSync instance URL or self-hosted endpoint]",
authenticator = MyAuthenticator(),
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
)
}
/**
* Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
* expire or is rejected.
*/
open class MyAuthenticator : Authenticator {
private var token: String? = null
override suspend fun resolveCredentials(): String = token ?: fetchAuthToken().also { token = it }
/**
* The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
* resolveCredentials() call must return a new token. This cache suits a token that you request from your backend.
* If fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you
* can return that token without this cache and ask the library to refresh it here instead. See
* https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
*/
override fun invalidateCredentials() {
token = null
}
/**
* Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
* Supabase and Firebase tokens can be used as they are:
* - https://docs.powersync.com/configuration/auth/supabase-auth
* - https://docs.powersync.com/configuration/auth/firebase-auth
* To get started without an auth provider, use a development token:
* https://docs.powersync.com/configuration/auth/development-tokens
*/
private suspend fun fetchAuthToken(): String = "An authentication token"
}
2
Add Uploads
PowerSyncUploader.kt
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires PowerSync Kotlin SDK 1.16.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in postTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
//
// Uses the Ktor client and kotlinx.serialization JSON, which the PowerSync SDK already builds on. Add
// them to your module if they are not there yet: https://ktor.io/docs/client-engines.html
import com.powersync.PowerSyncDatabase
import com.powersync.connectors.Authenticator
import com.powersync.connectors.MutationUploader
import com.powersync.db.crud.CrudTransaction
import io.ktor.client.HttpClient
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.http.isSuccess
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
/** Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself. */
private const val BACKEND_URL = "http://localhost:6060"
/** Abort a write endpoint request after this many milliseconds. */
private const val REQUEST_TIMEOUT_MS = 30_000L
/**
* Connects `db` with the authenticator and this uploader. Use this instead of the connect() in your
* authenticator file, and delete that one.
*/
suspend fun connect(db: PowerSyncDatabase) {
// MyAuthenticator is the authenticator from your read setup.
val authenticator = MyAuthenticator()
db.connect(
endpoint = "[Your PowerSync instance URL or self-hosted endpoint]",
authenticator = authenticator,
uploader = MyMutationUploader(authenticator),
)
}
/**
* @param authenticator Supplies the token for write endpoint requests. The write endpoint accepts the same JWTs
* as your PowerSync instance, so this is the same authenticator that you connect with.
*/
open class MyMutationUploader(
private val authenticator: Authenticator,
private val httpClient: HttpClient = HttpClient(),
) : MutationUploader {
/**
* Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
* keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
* and the SDK retries after a delay.
* See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
*/
override suspend fun uploadMutations(onDatabase: PowerSyncDatabase) {
val transaction = onDatabase.getNextCrudTransaction() ?: return
val result = try {
postTransaction(transaction)
} catch (e: AuthenticationException) {
// Fetch a new token before the next attempt.
authenticator.invalidateCredentials()
throw e
}
when (val status = result.status) {
"success" -> {}
"retryable_error" -> throw Exception(result.message ?: "Retryable error")
"fatal_error" -> {
val requiresClientHandling = result["requires_client_handling"]?.jsonPrimitive?.boolean == true
if (requiresClientHandling && onFatalTransaction(transaction, result) == FatalDecision.RETAIN) {
throw Exception("Transaction retained after ${result.errorCode}")
}
// A fatal error that the write endpoint already handled (for example, with a dead-letter hook), or one
// that onFatalTransaction() chose to discard.
}
else -> throw Exception("Unexpected transaction result: $status")
}
transaction.complete(null)
}
/**
* Called for fatal errors that the write endpoint leaves to the client. RETAIN keeps the transaction queued,
* which blocks later uploads, and the SDK calls this again on its next attempt. Return COMPLETE to discard
* the transaction, for example after telling the user.
* See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
*/
protected open suspend fun onFatalTransaction(transaction: CrudTransaction, result: JsonObject): FatalDecision {
println("Transaction needs client handling: ${result.errorCode} ${result.message}")
return FatalDecision.RETAIN
}
/**
* Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined
* by the write endpoint's OpenAPI spec:
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
*/
private suspend fun postTransaction(transaction: CrudTransaction): JsonObject {
val body = buildJsonObject {
putJsonArray("transactions") {
add(
buildJsonObject {
transaction.transactionId?.let { put("transaction_id", it) }
putJsonArray("crud") {
for (op in transaction.crud) {
add(
buildJsonObject {
put("id", op.id)
put("op", op.op.toJson()) // PUT, PATCH or DELETE
put("table", op.table)
op.transactionId?.let { put("transaction_id", it) }
// Changed columns for PUT and PATCH
op.opData?.let { put("op_data", JsonObject(it.jsonValues)) }
},
)
}
}
},
)
}
}
// withTimeoutOrNull, not withTimeout: a timeout must surface as an ordinary error, not a cancellation.
val response = withTimeoutOrNull(REQUEST_TIMEOUT_MS) {
httpClient.post("$BACKEND_URL/api/data") {
contentType(ContentType.Application.Json)
bearerAuth(authenticator.resolveCredentials())
setBody(body.toString())
}
} ?: throw Exception("Write endpoint request timed out")
val text = response.bodyAsText()
val status = response.status.value
if (!response.status.isSuccess()) {
// Every non-2xx response from the write endpoint has the shape { message }.
val message = runCatching { Json.parseToJsonElement(text).jsonObject.message }.getOrNull()
?: response.status.description
if (status == 401 || status == 403) {
throw AuthenticationException("Write endpoint rejected the token ($status): $message")
}
throw Exception("Write endpoint request failed ($status): $message")
}
// One result per transaction sent. A result's status is "success", "retryable_error", "fatal_error" or
// "not_attempted". A fatal error has requires_client_handling and failed_operation.error_code.
val results = Json.parseToJsonElement(text).jsonObject["results"] as? JsonArray
if (results == null || results.size != 1) {
throw Exception("Expected one result for one transaction")
}
return results[0].jsonObject
}
}
enum class FatalDecision { RETAIN, COMPLETE }
/** Thrown when the write endpoint rejects the token (401 or 403). */
class AuthenticationException(message: String) : Exception(message)
private val JsonObject.status: String? get() = this["status"]?.jsonPrimitive?.contentOrNull
private val JsonObject.message: String? get() = this["message"]?.jsonPrimitive?.contentOrNull
private val JsonObject.errorCode: String?
get() = this["failed_operation"]?.jsonObject?.get("error_code")?.jsonPrimitive?.contentOrNull
1
Connect for Downloads
PowerSyncAuthenticator.swift
// Requires PowerSync Swift SDK 1.17.0 or later.
import PowerSync
/// Connects `db` to your PowerSync instance with this authenticator.
func connect(db: PowerSyncDatabaseProtocol) async throws {
try await db.connect(
endpoint: "[Your PowerSync instance URL or self-hosted endpoint]",
authenticator: MyAuthenticator(),
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
options: ConnectOptions()
)
}
/// Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
/// expire or is rejected.
/// An actor, because the SDK requires a Sendable authenticator and this one caches a token.
actor MyAuthenticator: Authenticator {
private var token: String?
func resolveCredentials() async throws -> String {
if let token {
return token
}
let token = try await fetchAuthToken()
self.token = token
return token
}
/// The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
/// resolveCredentials() call must return a new token. This cache suits a token that you request from your backend.
/// If fetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you
/// can return that token without this cache and ask the library to refresh it here instead. See
/// https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
func invalidateCredentials() async {
token = nil
}
/// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
/// Supabase and Firebase tokens can be used as they are:
/// - https://docs.powersync.com/configuration/auth/supabase-auth
/// - https://docs.powersync.com/configuration/auth/firebase-auth
/// To get started without an auth provider, use a development token:
/// https://docs.powersync.com/configuration/auth/development-tokens
private func fetchAuthToken() async throws -> String {
return "An authentication token"
}
}
2
Add Uploads
PowerSyncUploader.swift
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires PowerSync Swift SDK 1.17.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in postTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
import Foundation
import PowerSync
/// Base URL of the write endpoint. On a phone or simulator, `localhost` refers to the device itself.
private let backendUrl = URL(string: "http://localhost:6060")!
/// Abort a write endpoint request after this many seconds.
private let requestTimeout: TimeInterval = 30
/// Connects `db` with the authenticator and this uploader. Use this instead of the connect() in your
/// authenticator file, and delete that one.
func connect(db: PowerSyncDatabaseProtocol) async throws {
// MyAuthenticator is the authenticator from your read setup.
let authenticator = MyAuthenticator()
try await db.connect(
endpoint: "[Your PowerSync instance URL or self-hosted endpoint]",
authenticator: authenticator,
mutationUploader: MyMutationUploader(authenticator: authenticator).upload,
options: ConnectOptions()
)
}
/// An actor, because the SDK requires a Sendable upload callback.
actor MyMutationUploader {
private let authenticator: Authenticator
/// - Parameter authenticator: Supplies the token for write endpoint requests. The write endpoint accepts the same
/// JWTs as your PowerSync instance, so this is the same authenticator that you connect with.
init(authenticator: Authenticator) {
self.authenticator = authenticator
}
/// Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
/// keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
/// and the SDK retries after a delay.
/// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
func upload(database: PowerSyncDatabaseProtocol) async throws {
guard let transaction = try await database.getNextCrudTransaction() else {
return
}
let result: TransactionResult
do {
result = try await postTransaction(transaction)
} catch let error as AuthenticationError {
// Fetch a new token before the next attempt.
await authenticator.invalidateCredentials()
throw error
}
switch result.status {
case "success":
break
case "retryable_error":
throw UploadError(message: result.message ?? "Retryable error")
case "fatal_error":
if result.requiresClientHandling == true,
await onFatalTransaction(transaction, result) == .retain {
throw UploadError(message: "Transaction retained after \(result.failedOperation?.errorCode ?? "")")
}
// A fatal error that the write endpoint already handled (for example, with a dead-letter hook), or one that
// onFatalTransaction() chose to discard.
default:
throw UploadError(message: "Unexpected transaction result: \(result.status)")
}
try await transaction.complete()
}
/// Called for fatal errors that the write endpoint leaves to the client. `.retain` keeps the transaction queued,
/// which blocks later uploads, and the SDK calls this again on its next attempt. Return `.complete` to discard
/// the transaction, for example after telling the user.
/// See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
func onFatalTransaction(_ transaction: CrudTransaction, _ result: TransactionResult) async -> FatalDecision {
print("Transaction needs client handling: \(result.failedOperation?.errorCode ?? "") \(result.message ?? "")")
return .retain
}
/// Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined
/// by the write endpoint's OpenAPI spec:
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
private func postTransaction(_ transaction: CrudTransaction) async throws -> TransactionResult {
let body = TransactionBatch(transactions: [
TransactionBody(
transactionId: transaction.transactionId,
crud: transaction.crud.map { op in
CrudBody(
id: op.id,
op: op.op.rawValue, // PUT, PATCH or DELETE
table: op.table,
transactionId: op.transactionId,
opData: op.opDataTyped // Changed columns for PUT and PATCH, nil for DELETE
)
}
),
])
var request = URLRequest(url: backendUrl.appendingPathComponent("api/data"))
request.httpMethod = "POST"
request.timeoutInterval = requestTimeout
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(try await authenticator.resolveCredentials())", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONEncoder().encode(body)
let (data, response) = try await URLSession.shared.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
guard (200..<300).contains(status) else {
// Every non-2xx response from the write endpoint has the shape { message }.
let message = (try? JSONDecoder().decode(MessageResponse.self, from: data))?.message
?? HTTPURLResponse.localizedString(forStatusCode: status)
if status == 401 || status == 403 {
throw AuthenticationError(message: "Write endpoint rejected the token (\(status)): \(message)")
}
throw UploadError(message: "Write endpoint request failed (\(status)): \(message)")
}
let results = try JSONDecoder().decode(TransactionBatchResponse.self, from: data).results
guard results.count == 1 else {
throw UploadError(message: "Expected one result for one transaction")
}
return results[0]
}
}
enum FatalDecision {
case retain, complete
}
// Request and response types from the write endpoint's OpenAPI spec.
private struct TransactionBatch: Encodable {
let transactions: [TransactionBody]
}
private struct TransactionBody: Encodable {
let transactionId: Int64?
let crud: [CrudBody]
enum CodingKeys: String, CodingKey {
case transactionId = "transaction_id", crud
}
}
private struct CrudBody: Encodable {
let id: String
let op: String
let table: String
let transactionId: Int64?
let opData: JsonParam?
enum CodingKeys: String, CodingKey {
case id, op, table, transactionId = "transaction_id", opData = "op_data"
}
}
private struct TransactionBatchResponse: Decodable {
/// One result per transaction sent.
let results: [TransactionResult]
}
/// `status` is "success", "retryable_error", "fatal_error" or "not_attempted".
struct TransactionResult: Decodable, Sendable {
let status: String
let message: String?
/// For a fatal error. True: the write endpoint leaves the decision to the client. False: it already handled the failure.
let requiresClientHandling: Bool?
let failedOperation: FailedOperation?
enum CodingKeys: String, CodingKey {
case status, message, requiresClientHandling = "requires_client_handling", failedOperation = "failed_operation"
}
}
struct FailedOperation: Decodable, Sendable {
/// For example "UNIQUE_VIOLATION", "INVALID_DATA", "UNAUTHORIZED", or an application-defined code.
let errorCode: String
let message: String?
enum CodingKeys: String, CodingKey {
case errorCode = "error_code", message
}
}
private struct MessageResponse: Decodable {
let message: String
}
struct UploadError: Error {
let message: String
}
/// Thrown when the write endpoint rejects the token (401 or 403).
struct AuthenticationError: Error {
let message: String
}
1
Connect for Downloads
PowerSyncAuthenticator.cs
// Requires PowerSync.Common 1.0.1 or later.
using System.Threading.Tasks;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
/// <summary>
/// Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is about to
/// expire or is rejected.
/// </summary>
public class MyAuthenticator : IAuthenticator
{
/// <summary>
/// Connects <paramref name="db"/> to your PowerSync instance with this authenticator.
/// </summary>
public static async Task Connect(IPowerSyncDatabase db)
{
await db.Connect(
"[Your PowerSync instance URL or self-hosted endpoint]",
new MyAuthenticator(),
// To upload local writes, pass your mutation uploader here instead of null:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
null);
}
private string? _token;
public async Task<string> ResolveCredentials()
{
return _token ??= await FetchAuthToken();
}
/// <summary>
/// The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
/// ResolveCredentials() call must return a new token. This cache suits a token that you request from your backend.
/// If FetchAuthToken() returns a token that your auth library stores and refreshes, such as a Supabase session, you
/// can return that token without this cache and ask the library to refresh it here instead. See
/// https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
/// </summary>
public void InvalidateCredentials()
{
_token = null;
}
/// <summary>
/// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
/// Supabase and Firebase tokens can be used as they are:
/// - https://docs.powersync.com/configuration/auth/supabase-auth
/// - https://docs.powersync.com/configuration/auth/firebase-auth
/// To get started without an auth provider, use a development token:
/// https://docs.powersync.com/configuration/auth/development-tokens
/// </summary>
private Task<string> FetchAuthToken()
{
return Task.FromResult("An authentication token");
}
}
2
Add Uploads
PowerSyncUploader.cs
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires PowerSync.Common 1.0.1 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in PostTransaction() to match it,
// or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
using PowerSync.Common.DB.Crud;
/// <param name="authenticator">
/// Supplies the token for write endpoint requests. The write endpoint accepts the same JWTs as your PowerSync
/// instance, so this is the same authenticator that you connect with.
/// </param>
public class MyMutationUploader(IAuthenticator authenticator) : IMutationUploader
{
/// <summary>
/// Connects <paramref name="db"/> with the authenticator and this uploader. Use this instead of the Connect()
/// in your authenticator file, and delete that one.
/// </summary>
public static async Task Connect(IPowerSyncDatabase db)
{
// MyAuthenticator is the authenticator from your read setup.
var authenticator = new MyAuthenticator();
await db.Connect(
"[Your PowerSync instance URL or self-hosted endpoint]",
authenticator,
new MyMutationUploader(authenticator));
}
// Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself.
private const string BackendUrl = "http://localhost:6060";
private static readonly JsonSerializerOptions JsonOptions = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
// Aborts a write endpoint request after 30 seconds.
private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) };
/// <summary>
/// Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on
/// keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued,
/// and the SDK retries after a delay.
/// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
/// </summary>
public async Task UploadMutations(IPowerSyncDatabase database)
{
var transaction = await database.GetNextCrudTransaction();
if (transaction == null)
{
return;
}
TransactionResult result;
try
{
result = await PostTransaction(transaction);
}
catch (AuthenticationException)
{
// Fetch a new token before the next attempt.
authenticator.InvalidateCredentials();
throw;
}
switch (result.Status)
{
case "success":
break;
case "retryable_error":
throw new Exception(result.Message ?? "Retryable error");
case "fatal_error":
if (result.RequiresClientHandling == true &&
await OnFatalTransaction(transaction, result) == FatalDecision.Retain)
{
throw new Exception($"Transaction retained after {result.FailedOperation?.ErrorCode}");
}
// A fatal error that the write endpoint already handled (for example, with a dead-letter hook), or one
// that OnFatalTransaction() chose to discard.
break;
default:
throw new Exception($"Unexpected transaction result: {result.Status}");
}
await transaction.Complete();
}
/// <summary>
/// Called for fatal errors that the write endpoint leaves to the client. Retain keeps the transaction queued,
/// which blocks later uploads, and the SDK calls this again on its next attempt. Return Complete to discard
/// the transaction, for example after telling the user.
/// See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
/// </summary>
protected virtual Task<FatalDecision> OnFatalTransaction(CrudTransaction transaction, TransactionResult result)
{
Console.Error.WriteLine($"Transaction needs client handling: {result.FailedOperation?.ErrorCode} {result.Message}");
return Task.FromResult(FatalDecision.Retain);
}
/// <summary>
/// Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined
/// by the write endpoint's OpenAPI spec:
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
/// </summary>
private async Task<TransactionResult> PostTransaction(CrudTransaction transaction)
{
var body = new TransactionBatch([
new TransactionBody(
transaction.TransactionId,
transaction.Crud.Select(op => new CrudBody(
op.Id,
op.Op.ToString(), // PUT, PATCH or DELETE
op.Table,
op.TransactionId,
op.OpData // Changed columns for PUT and PATCH, null for DELETE
)).ToList())
]);
using var request = new HttpRequestMessage(HttpMethod.Post, $"{BackendUrl}/api/data")
{
Content = JsonContent.Create(body, options: JsonOptions)
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await authenticator.ResolveCredentials());
using var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
// Every non-2xx response from the write endpoint has the shape { message }.
string? message = null;
try
{
message = (await response.Content.ReadFromJsonAsync<MessageResponse>())?.Message;
}
catch (JsonException)
{
}
message ??= response.ReasonPhrase;
var status = (int)response.StatusCode;
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
throw new AuthenticationException($"Write endpoint rejected the token ({status}): {message}");
}
throw new HttpRequestException($"Write endpoint request failed ({status}): {message}");
}
var results = (await response.Content.ReadFromJsonAsync<TransactionBatchResponse>())?.Results;
if (results is not { Count: 1 })
{
throw new Exception("Expected one result for one transaction");
}
return results[0];
}
}
public enum FatalDecision { Retain, Complete }
// Request and response types from the write endpoint's OpenAPI spec.
record TransactionBatch(
[property: JsonPropertyName("transactions")] List<TransactionBody> Transactions);
record TransactionBody(
[property: JsonPropertyName("transaction_id")] long? TransactionId,
[property: JsonPropertyName("crud")] List<CrudBody> Crud);
record CrudBody(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("op")] string Op,
[property: JsonPropertyName("table")] string Table,
[property: JsonPropertyName("transaction_id")] long? TransactionId,
[property: JsonPropertyName("op_data")] Dictionary<string, object>? OpData);
record TransactionBatchResponse(
// One result per transaction sent.
[property: JsonPropertyName("results")] List<TransactionResult> Results);
// Status is "success", "retryable_error", "fatal_error" or "not_attempted".
// For a fatal error, RequiresClientHandling is true if the write endpoint leaves the decision to the client, and false
// if it already handled the failure.
public record TransactionResult(
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("message")] string? Message = null,
[property: JsonPropertyName("requires_client_handling")] bool? RequiresClientHandling = null,
[property: JsonPropertyName("failed_operation")] FailedOperation? FailedOperation = null);
// ErrorCode is, for example, "UNIQUE_VIOLATION", "INVALID_DATA", "UNAUTHORIZED", or an application-defined code.
public record FailedOperation(
[property: JsonPropertyName("error_code")] string ErrorCode,
[property: JsonPropertyName("message")] string? Message = null);
record MessageResponse([property: JsonPropertyName("message")] string Message);
// Thrown when the write endpoint rejects the token (401 or 403).
public class AuthenticationException(string message) : Exception(message);
1
Connect for Downloads
src/authenticator.rs
// Requires powersync 0.2.0 or later.
// Uses the async-trait crate: cargo add async-trait
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use powersync::error::PowerSyncError;
use powersync::{Authenticator, PowerSyncDatabase, SyncOptions};
/// Connects `db` to your PowerSync instance with this authenticator.
pub async fn connect(db: &PowerSyncDatabase) {
// To upload local writes, use SyncOptions::new(...) and also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
db.connect(SyncOptions::download_only(
"[Your PowerSync instance URL or self-hosted endpoint]",
MyAuthenticator::default(),
))
.await;
}
/// Provides the token that the SDK sends to your PowerSync instance. The token is cached until it is rejected.
#[derive(Clone, Default)]
pub struct MyAuthenticator {
token: Arc<Mutex<Option<Arc<String>>>>,
}
impl MyAuthenticator {
/// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview
/// Supabase and Firebase tokens can be used as they are:
/// - https://docs.powersync.com/configuration/auth/supabase-auth
/// - https://docs.powersync.com/configuration/auth/firebase-auth
/// To get started without an auth provider, use a development token:
/// https://docs.powersync.com/configuration/auth/development-tokens
async fn fetch_auth_token(&self) -> Result<String, PowerSyncError> {
Ok("An authentication token".to_string())
}
}
#[async_trait]
impl Authenticator for MyAuthenticator {
async fn resolve_credentials(&self) -> Result<Arc<String>, PowerSyncError> {
if let Some(token) = self.token.lock().unwrap().clone() {
return Ok(token);
}
let token = Arc::new(self.fetch_auth_token().await?);
*self.token.lock().unwrap() = Some(token.clone());
Ok(token)
}
/// The SDK calls this before the token expires and when the PowerSync Service rejects it, and the next
/// `resolve_credentials()` call must return a new token. This cache suits a token that you request from your
/// backend. If `fetch_auth_token()` returns a token that your auth library stores and refreshes, such as a Supabase
/// session, you can return that token without this cache and ask the library to refresh it here instead. See
/// https://docs.powersync.com/configuration/app-backend/client-side-integration#when-resolvecredentials-is-called
fn invalidate_credentials(&self) {
*self.token.lock().unwrap() = None;
}
}
2
Add Uploads
src/uploader.rs
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// Requires powersync 0.2.0 or later.
// Set up the write endpoint: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation
// If your backend has a different API, change the request and response handling in post_transaction() to match
// it, or have a coding agent write the uploader for your API:
// https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent
// For several transactions per request and client-side backoff, see the full reference uploader:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowerSyncUploader.singlefile.ts
//
// Uses the `reqwest` feature of the powersync crate, plus these crates:
// cargo add async-trait futures-lite serde_json serde --features serde/derive
// cargo add reqwest@0.13 --features json # The same major version as the powersync crate uses
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use futures_lite::StreamExt;
use powersync::error::PowerSyncError;
use powersync::{Authenticator, CrudTransaction, MutationUploader, PowerSyncDatabase, SyncOptions, UpdateType};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
// MyAuthenticator is the authenticator from your read setup.
use crate::authenticator::MyAuthenticator;
/// Base URL of the write endpoint. On a phone or emulator, `localhost` refers to the device itself.
const BACKEND_URL: &str = "http://localhost:6060";
/// Abort a write endpoint request after this long.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// Connects `db` with the authenticator and this uploader. Use this instead of the `connect()` in your
/// authenticator file, and delete that one.
pub async fn connect(db: &PowerSyncDatabase) {
let authenticator = MyAuthenticator::default();
db.connect(SyncOptions::new(
"[Your PowerSync instance URL or self-hosted endpoint]",
authenticator.clone(),
MyMutationUploader::new(db.clone(), authenticator),
))
.await;
}
pub struct MyMutationUploader {
db: PowerSyncDatabase,
authenticator: Arc<dyn Authenticator>,
http: reqwest::Client,
}
impl MyMutationUploader {
/// `authenticator` supplies the token for write endpoint requests. The write endpoint accepts the same JWTs as
/// your PowerSync instance, so this is the same authenticator that you connect with.
pub fn new(db: PowerSyncDatabase, authenticator: impl Authenticator + 'static) -> Self {
Self {
db,
authenticator: Arc::new(authenticator),
http: reqwest::Client::new(),
}
}
/// Called for fatal errors that the write endpoint leaves to the client. `Retain` keeps the transaction queued,
/// which blocks later uploads, and the SDK calls this again on its next attempt. Return `Complete` to discard
/// the transaction, for example after telling the user.
/// See https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/error-handling.md
async fn on_fatal_transaction(&self, _transaction: &CrudTransaction<'_>, result: &TransactionResult) -> FatalDecision {
eprintln!("Transaction needs client handling: {:?} {:?}", result.error_code(), result.message);
FatalDecision::Retain
}
/// Sends one transaction to POST /api/data and returns its result. The request and response shapes are
/// defined by the write endpoint's OpenAPI spec:
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-endpoint.openapi.yaml
async fn post_transaction(&self, transaction: &CrudTransaction<'_>) -> Result<TransactionResult, PowerSyncError> {
let body = TransactionBatch {
transactions: vec![TransactionBody {
transaction_id: transaction.id,
crud: transaction
.crud
.iter()
.map(|op| CrudBody {
id: &op.id,
op: &op.update_type, // "PUT", "PATCH" or "DELETE"
table: &op.table,
transaction_id: op.transaction_id,
op_data: op.data.as_ref(), // Changed columns for PUT and PATCH, None for DELETE
})
.collect(),
}],
};
let token = self.authenticator.resolve_credentials().await?;
let response = self
.http
.post(format!("{BACKEND_URL}/api/data"))
.bearer_auth(token)
.json(&body)
.timeout(REQUEST_TIMEOUT)
.send()
.await?;
let status = response.status();
if !status.is_success() {
// Every non-2xx response from the write endpoint has the shape { message }.
let message = response
.json::<MessageResponse>()
.await
.map(|body| body.message)
.unwrap_or_else(|_| status.to_string());
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
// Fetch a new token before the next attempt.
self.authenticator.invalidate_credentials();
return Err(upload_error(format!("Write endpoint rejected the token ({status}): {message}")));
}
return Err(upload_error(format!("Write endpoint request failed ({status}): {message}")));
}
let mut results = response.json::<TransactionBatchResponse>().await?.results;
if results.len() != 1 {
return Err(upload_error("Expected one result for one transaction".to_string()));
}
Ok(results.remove(0))
}
}
#[async_trait]
impl MutationUploader for MyMutationUploader {
/// Uploads queued transactions, oldest first. The SDK calls this when the upload queue has writes.
/// Returning an error keeps the transaction queued, and the SDK retries after a delay.
/// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called
async fn upload(&self) -> Result<(), PowerSyncError> {
let mut transactions = self.db.crud_transactions();
while let Some(transaction) = transactions.try_next().await? {
let result = self.post_transaction(&transaction).await?;
match result.status.as_str() {
"success" => {}
"retryable_error" => {
return Err(upload_error(result.message.unwrap_or_else(|| "Retryable error".to_string())));
}
"fatal_error" => {
if result.requires_client_handling == Some(true)
&& self.on_fatal_transaction(&transaction, &result).await == FatalDecision::Retain
{
return Err(upload_error(format!(
"Transaction retained after {:?}",
result.error_code()
)));
}
// A fatal error that the write endpoint already handled (for example, with a dead-letter hook), or
// one that on_fatal_transaction() chose to discard.
}
status => return Err(upload_error(format!("Unexpected transaction result: {status}"))),
}
transaction.complete().await?;
}
Ok(())
}
}
#[derive(PartialEq)]
pub enum FatalDecision {
Retain,
Complete,
}
fn upload_error(message: String) -> PowerSyncError {
PowerSyncError::upload_error(std::io::Error::other(message))
}
// Request and response types from the write endpoint's OpenAPI spec.
#[derive(Serialize)]
struct TransactionBatch<'a> {
transactions: Vec<TransactionBody<'a>>,
}
#[derive(Serialize)]
struct TransactionBody<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
transaction_id: Option<i64>,
crud: Vec<CrudBody<'a>>,
}
#[derive(Serialize)]
struct CrudBody<'a> {
id: &'a str,
op: &'a UpdateType,
table: &'a str,
transaction_id: i64,
#[serde(skip_serializing_if = "Option::is_none")]
op_data: Option<&'a Map<String, Value>>,
}
#[derive(Deserialize)]
struct TransactionBatchResponse {
/// One result per transaction sent.
results: Vec<TransactionResult>,
}
/// `status` is "success", "retryable_error", "fatal_error" or "not_attempted".
#[derive(Deserialize)]
pub struct TransactionResult {
pub status: String,
pub message: Option<String>,
/// For a fatal error. True: the write endpoint leaves the decision to the client. False: it already handled the
/// failure.
pub requires_client_handling: Option<bool>,
pub failed_operation: Option<FailedOperation>,
}
impl TransactionResult {
fn error_code(&self) -> Option<&str> {
self.failed_operation.as_ref().map(|op| op.error_code.as_str())
}
}
/// `error_code` is, for example, "UNIQUE_VIOLATION", "INVALID_DATA", "UNAUTHORIZED", or an application-defined
/// code.
#[derive(Deserialize)]
pub struct FailedOperation {
pub error_code: String,
pub message: Option<String>,
}
#[derive(Deserialize)]
struct MessageResponse {
message: String,
}
Supabase
The authenticator signs users in with Supabase Auth and gives the SDK their access token. The uploader writes to Supabase with the Supabase client SDK, which is the PostgREST route. There is no Supabase example for Rust. To write through the Supabase Edge Function instead, use the Supabase authenticator with the reference write endpoint uploader from Custom Backend.- JavaScript
- TypeScript
- React Native
- Dart
- Kotlin
- Swift
- .NET
1
Connect for Downloads
SupabaseAuthenticator.js
// Requires @powersync/web 2.6.0 or later.
import { BaseObserver } from '@powersync/web';
import { createClient } from '@supabase/supabase-js';
// Signs users in with Supabase Auth and gives the SDK their access token. Connect with:
// await db.connect({ powerSyncEndpoint: authenticator.config.powersyncUrl, authenticator });
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
export class SupabaseAuthenticator extends BaseObserver {
constructor() {
super();
this.cachedToken = null;
this.config = {
supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
powersyncUrl: import.meta.env.VITE_POWERSYNC_URL,
supabaseAnonKey: import.meta.env.VITE_SUPABASE_ANON_KEY
};
this.client = createClient(this.config.supabaseUrl, this.config.supabaseAnonKey, {
auth: {
persistSession: true
}
});
this.currentSession = null;
this.ready = false;
}
async init() {
if (this.ready) {
return;
}
const sessionResponse = await this.client.auth.getSession();
this.updateSession(sessionResponse.data.session);
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
async login(username, password) {
const {
data: { session },
error
} = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.updateSession(session);
}
/**
* Returns the Supabase access token for sync, cached until the SDK calls invalidateCredentials().
* After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes
* the session when it expires within 90 seconds.
*/
async resolveCredentials() {
if (this.cachedToken) {
return this.cachedToken;
}
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
this.cachedToken = session.access_token;
return this.cachedToken;
}
/** Called by the SDK before the token expires and when the PowerSync Service rejects it. */
invalidateCredentials() {
this.cachedToken = null;
}
updateSession(session) {
this.currentSession = session;
this.cachedToken = null; // A new session has a new token.
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
2
Add Uploads
SupabaseUploader.js
// Requires @powersync/web 2.6.0 or later.
import { UpdateType } from '@powersync/web';
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// Pass it the Supabase client from your SupabaseAuthenticator, and connect with:
// await db.connect({
// powerSyncEndpoint: authenticator.config.powersyncUrl,
// authenticator,
// upload: new SupabaseUploader(authenticator.client).upload
// });
export class SupabaseUploader {
constructor(client) {
this.client = client;
// connect() passes upload() to the SDK on its own, so bind it to this uploader.
this.upload = this.upload.bind(this);
}
/** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */
async upload({ database }) {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result;
switch (op.op) {
case UpdateType.PUT: {
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
}
case UpdateType.PATCH:
result = await table.update(op.opData).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not update Supabase. Received error: ${result.error.message}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
}
}
1
Connect for Downloads
SupabaseAuthenticator.ts
// Requires @powersync/web 2.6.0 or later.
import { BaseObserver, type Authenticator } from '@powersync/web';
import { Session, SupabaseClient, createClient } from '@supabase/supabase-js';
export type SupabaseConfig = {
supabaseUrl: string;
supabaseAnonKey: string;
powersyncUrl: string;
};
export type SupabaseAuthenticatorListener = {
initialized: () => void;
sessionStarted: (session: Session) => void;
};
// Signs users in with Supabase Auth and gives the SDK their access token. Connect with:
// await db.connect({ powerSyncEndpoint: authenticator.config.powersyncUrl, authenticator });
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
export class SupabaseAuthenticator extends BaseObserver<SupabaseAuthenticatorListener> implements Authenticator {
readonly client: SupabaseClient;
readonly config: SupabaseConfig;
ready: boolean;
currentSession: Session | null;
private cachedToken: string | null = null;
constructor() {
super();
this.config = {
supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
powersyncUrl: import.meta.env.VITE_POWERSYNC_URL,
supabaseAnonKey: import.meta.env.VITE_SUPABASE_ANON_KEY
};
this.client = createClient(this.config.supabaseUrl, this.config.supabaseAnonKey, {
auth: {
persistSession: true
}
});
this.currentSession = null;
this.ready = false;
}
async init() {
if (this.ready) {
return;
}
const sessionResponse = await this.client.auth.getSession();
this.updateSession(sessionResponse.data.session);
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
async login(username: string, password: string) {
const {
data: { session },
error
} = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.updateSession(session);
}
/**
* Returns the Supabase access token for sync, cached until the SDK calls invalidateCredentials().
* After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes
* the session when it expires within 90 seconds.
*/
async resolveCredentials(): Promise<string> {
if (this.cachedToken) {
return this.cachedToken;
}
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
this.cachedToken = session.access_token;
return this.cachedToken;
}
/** Called by the SDK before the token expires and when the PowerSync Service rejects it. */
invalidateCredentials(): void {
this.cachedToken = null;
}
updateSession(session: Session | null) {
this.currentSession = session;
this.cachedToken = null; // A new session has a new token.
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
2
Add Uploads
SupabaseUploader.ts
// Requires @powersync/web 2.6.0 or later.
import { UpdateType, type CrudEntry, type MutationUploader } from '@powersync/web';
import { SupabaseClient } from '@supabase/supabase-js';
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// Pass it the Supabase client from your SupabaseAuthenticator, and connect with:
// await db.connect({
// powerSyncEndpoint: authenticator.config.powersyncUrl,
// authenticator,
// upload: new SupabaseUploader(authenticator.client).upload
// });
export class SupabaseUploader {
constructor(private readonly client: SupabaseClient) {}
/** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */
readonly upload: MutationUploader = async ({ database }) => {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp: CrudEntry | null = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result: any;
switch (op.op) {
case UpdateType.PUT:
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
case UpdateType.PATCH:
result = await table.update(op.opData ?? {}).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not update Supabase. Received error: ${result.error.message}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex: any) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
};
}
1
Connect for Downloads
SupabaseAuthenticator.ts
// Requires @powersync/react-native 2.4.0 or later.
import type { Authenticator } from '@powersync/react-native';
import { SupabaseClient, createClient } from '@supabase/supabase-js';
import { AppConfig } from './AppConfig';
import { SupabaseStorageAdapter } from '../storage/SupabaseStorageAdapter';
import { System } from '../powersync/system';
// Signs users in with Supabase Auth and gives the SDK their access token. Connect with:
// await db.connect({ powerSyncEndpoint: AppConfig.powersyncUrl, authenticator });
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
export class SupabaseAuthenticator implements Authenticator {
client: SupabaseClient;
storage: SupabaseStorageAdapter;
private cachedToken: string | null = null;
constructor(protected system: System) {
this.client = createClient(AppConfig.supabaseUrl, AppConfig.supabaseAnonKey, {
auth: {
persistSession: true,
storage: this.system.kvStorage
}
});
this.storage = new SupabaseStorageAdapter({ client: this.client });
}
async login(username: string, password: string) {
const { error } = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.cachedToken = null; // A new session has a new token.
}
async userId() {
const {
data: { session },
} = await this.client.auth.getSession();
return session?.user.id;
}
/**
* Returns the Supabase access token for sync, cached until the SDK calls invalidateCredentials().
* After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes
* the session when it expires within 90 seconds.
*/
async resolveCredentials(): Promise<string> {
if (this.cachedToken) {
return this.cachedToken;
}
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
this.cachedToken = session.access_token;
return this.cachedToken;
}
/** Called by the SDK before the token expires and when the PowerSync Service rejects it. */
invalidateCredentials(): void {
this.cachedToken = null;
}
}
2
Add Uploads
SupabaseUploader.ts
// Requires @powersync/react-native 2.4.0 or later.
import { UpdateType, type CrudEntry, type MutationUploader } from '@powersync/react-native';
import { SupabaseClient } from '@supabase/supabase-js';
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// Pass it the Supabase client from your SupabaseAuthenticator, and connect with:
// await db.connect({
// powerSyncEndpoint: AppConfig.powersyncUrl,
// authenticator,
// upload: new SupabaseUploader(authenticator.client).upload
// });
export class SupabaseUploader {
constructor(private readonly client: SupabaseClient) {}
/** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */
readonly upload: MutationUploader = async ({ database }) => {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp: CrudEntry | null = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result: any = null;
switch (op.op) {
case UpdateType.PUT:
// eslint-disable-next-line no-case-declarations
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
case UpdateType.PATCH:
result = await table.update(op.opData ?? {}).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not ${op.op} data to Supabase error: ${JSON.stringify(result)}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex: any) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
};
}
1
Connect for Downloads
lib/supabase_authenticator.dart
// Requires powersync 2.6.0 or later.
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import './app_config.dart';
import './models/schema.dart';
import './supabase.dart';
/// Use Supabase for authentication.
// Gives the SDK the signed-in user's Supabase access token. openDatabase() below connects with:
// db.connect(connector: ConnectRequest.downloadOnly(endpoint: AppConfig.powersyncUrl, authenticator: authenticator));
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
class SupabaseAuthenticator implements Authenticator {
Future<void>? _refreshFuture;
String? _cachedToken;
/// Returns the Supabase access token for sync, cached until the SDK calls
/// [invalidateCredentials]. The SDK calls it when the token expires or the
/// PowerSync Service rejects it, and this method then waits for the session
/// refresh that it starts.
/// `currentSession` doesn't refresh an expired session by itself, so an
/// expired session is refreshed here before its token is used.
@override
Future<String> resolveCredentials(Future<void> abortSignal) async {
if (_cachedToken case String token) {
return token;
}
// Wait for pending session refresh if any
await _refreshFuture;
// Use Supabase token for PowerSync
final auth = Supabase.instance.client.auth;
var session = auth.currentSession;
if (session == null) {
// Not logged in
throw StateError('Not logged in');
}
if (session.isExpired) {
// Throws if the refresh fails. The SDK then retries after a delay.
session = (await auth.refreshSession()).session ?? session;
}
// Use the access token to authenticate against PowerSync
return _cachedToken = session.accessToken;
}
/// Clears the cached token after a session change.
void clearCachedToken() {
_cachedToken = null; // A new session has a new token.
}
@override
void invalidateCredentials() {
_cachedToken = null;
// Trigger a session refresh if auth fails on PowerSync.
// Generally, sessions should be refreshed automatically by Supabase.
// However, in some cases it can be a while before the session refresh is
// retried. We attempt to trigger the refresh as soon as we get an auth
// failure on PowerSync.
//
// This could happen if the device was offline for a while and the session
// expired, and nothing else attempt to use the session it in the meantime.
//
// Timeout the refresh call to avoid waiting for long retries,
// and ignore any errors. resolveCredentials retries the refresh if the
// session is still expired.
_refreshFuture = Supabase.instance.client.auth
.refreshSession()
.timeout(const Duration(seconds: 5))
.then((response) => null, onError: (error) => null);
}
}
/// Global reference to the database
late final PowerSyncDatabase db;
bool isLoggedIn() {
return Supabase.instance.client.auth.currentSession?.accessToken != null;
}
/// id of the user currently logged in
String? getUserId() {
return Supabase.instance.client.auth.currentSession?.user.id;
}
Future<String> getDatabasePath() async {
const dbFilename = 'powersync-demo.db';
// getApplicationSupportDirectory is not supported on Web
if (kIsWeb) {
return dbFilename;
}
final dir = await getApplicationSupportDirectory();
return join(dir.path, dbFilename);
}
Future<void> openDatabase() async {
// Open the local database
db = PowerSyncDatabase(
schema: schema, path: await getDatabasePath(), logger: attachedLogger);
await db.initialize();
await loadSupabase();
SupabaseAuthenticator? currentAuthenticator;
if (isLoggedIn()) {
// If the user is already logged in, connect immediately.
// Otherwise, connect once logged in.
currentAuthenticator = SupabaseAuthenticator();
db.connect(
connector: ConnectRequest.downloadOnly(
endpoint: AppConfig.powersyncUrl,
authenticator: currentAuthenticator));
}
Supabase.instance.client.auth.onAuthStateChange.listen((data) async {
final AuthChangeEvent event = data.event;
if (event == AuthChangeEvent.signedIn) {
// Connect to PowerSync when the user is signed in
currentAuthenticator = SupabaseAuthenticator();
db.connect(
connector: ConnectRequest.downloadOnly(
endpoint: AppConfig.powersyncUrl,
authenticator: currentAuthenticator!));
} else if (event == AuthChangeEvent.signedOut) {
// Implicit sign out - disconnect, but don't delete data
currentAuthenticator = null;
await db.disconnect();
} else if (event == AuthChangeEvent.tokenRefreshed) {
// Supabase token refreshed - PowerSync uses the new token on its next request.
currentAuthenticator?.clearCachedToken();
}
});
}
/// Explicit sign out - clear database and log out.
Future<void> logout() async {
await Supabase.instance.client.auth.signOut();
await db.disconnectAndClear();
}
2
Add Uploads
lib/supabase_uploader.dart
// Requires powersync 2.6.0 or later.
import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
final log = Logger('powersync-supabase');
/// Postgres Response codes that we cannot recover from by retrying.
final List<RegExp> fatalResponseCodes = [
// Class 22 — Data Exception
// Examples include data type mismatch.
RegExp(r'^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
RegExp(r'^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
RegExp(r'^42501$'),
];
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// To upload local writes, import this file in lib/supabase_authenticator.dart and change both
// ConnectRequest.downloadOnly(...) calls in openDatabase() to:
// ConnectRequest(
// endpoint: AppConfig.powersyncUrl,
// authenticator: currentAuthenticator!,
// uploader: SupabaseUploader())
class SupabaseUploader implements MutationUploader {
// Upload pending changes to Supabase.
@override
Future<void> upload(PowerSyncDatabase database, Future<void> abortSignal) async {
// This function is called whenever there is data to upload, whether the
// device is online or offline.
// If this call throws an error, it is retried periodically.
final transaction = await database.getNextCrudTransaction();
if (transaction == null) {
return;
}
final rest = Supabase.instance.client.rest;
CrudEntry? lastOp;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (var op in transaction.crud) {
lastOp = op;
final table = rest.from(op.table);
if (op.op == UpdateType.put) {
var data = Map<String, dynamic>.of(op.opData!);
data['id'] = op.id;
await table.upsert(data);
} else if (op.op == UpdateType.patch) {
await table.update(op.opData!).eq('id', op.id);
} else if (op.op == UpdateType.delete) {
await table.delete().eq('id', op.id);
}
}
// All operations successful.
await transaction.complete();
} on PostgrestException catch (e) {
if (e.code != null &&
fatalResponseCodes.any((re) => re.hasMatch(e.code!))) {
/// Instead of blocking the queue with these errors,
/// discard the (rest of the) transaction.
///
/// Note that these errors typically indicate a bug in the application.
/// If protecting against data loss is important, save the failing records
/// elsewhere instead of discarding, and/or notify the user.
log.severe('Data upload error - discarding $lastOp', e);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
rethrow;
}
}
}
}
1
Connect for Downloads
SupabaseAuthenticator.kt
// Requires PowerSync Kotlin SDK 1.16.1 or later, with the Supabase integration:
// implementation("com.powersync:connector-supabase:$powersyncVersion")
import com.powersync.PowerSyncDatabase
import com.powersync.connector.supabase.SupabaseAuthenticator
import io.github.jan.supabase.SupabaseClient
import io.github.jan.supabase.auth.Auth
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.status.SessionStatus
import io.github.jan.supabase.createSupabaseClient
import io.github.jan.supabase.postgrest.Postgrest
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filter
/** Creates the Supabase client that your app signs in with. PowerSync needs its Auth and Postgrest plugins. */
fun createSupabase(supabaseUrl: String, supabaseAnonKey: String): SupabaseClient =
createSupabaseClient(supabaseUrl, supabaseAnonKey) {
install(Auth)
install(Postgrest)
}
/**
* Connects `db` while a user is signed in to Supabase, and disconnects and clears local data when they sign out.
* Call this from a coroutine that lives as long as the database, for example at app startup.
*
* SupabaseAuthenticator sends the access token of the current Supabase session, which the Supabase client
* refreshes.
*/
suspend fun connect(db: PowerSyncDatabase, supabase: SupabaseClient, powerSyncUrl: String) {
val authenticator = SupabaseAuthenticator(supabase)
supabase.auth.sessionStatus
.filter { it is SessionStatus.Authenticated || it is SessionStatus.NotAuthenticated }
// The Supabase client reports Authenticated again after each token refresh. The SDK requests the new
// token itself, so only react when the user signs in or out.
.distinctUntilChangedBy { it is SessionStatus.Authenticated }
.collect { status ->
if (status is SessionStatus.Authenticated) {
// To upload local writes, also pass your mutation uploader here:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
db.connect(endpoint = powerSyncUrl, authenticator = authenticator)
} else {
db.disconnectAndClear()
}
}
}
2
Add Uploads
SupabaseUploader.kt
// Requires PowerSync Kotlin SDK 1.16.1 or later, with the Supabase integration:
// implementation("com.powersync:connector-supabase:$powersyncVersion")
import com.powersync.PowerSyncDatabase
import com.powersync.connector.supabase.SupabaseAuthenticator
import com.powersync.connector.supabase.SupabaseUploader
import io.github.jan.supabase.SupabaseClient
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.status.SessionStatus
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filter
/**
* Connects `db` with the authenticator and this uploader while a user is signed in to Supabase, and disconnects
* and clears local data when they sign out. Use this instead of the connect() in your authenticator file, and
* delete that one. Pass it the same `supabase` client from createSupabase(). Call this from a coroutine that lives as long as the database, for example at app startup.
*
* SupabaseUploader uploads writes through PostgREST, as the signed-in user, so your RLS policies apply to them.
* It discards a transaction that fails with a data exception (class 22), an integrity constraint violation
* (class 23), or insufficient privilege (42501), and retries other errors. To change this, override handleError().
* To change how each operation is sent, override uploadCrudEntry().
*/
suspend fun connect(db: PowerSyncDatabase, supabase: SupabaseClient, powerSyncUrl: String) {
val authenticator = SupabaseAuthenticator(supabase)
val uploader = SupabaseUploader(supabase)
supabase.auth.sessionStatus
.filter { it is SessionStatus.Authenticated || it is SessionStatus.NotAuthenticated }
// The Supabase client reports Authenticated again after each token refresh. The SDK requests the new
// token itself, so only react when the user signs in or out.
.distinctUntilChangedBy { it is SessionStatus.Authenticated }
.collect { status ->
if (status is SessionStatus.Authenticated) {
db.connect(endpoint = powerSyncUrl, authenticator = authenticator, uploader = uploader)
} else {
db.disconnectAndClear()
}
}
}
1
Connect for Downloads
SupabaseAuthenticator.swift
// Requires PowerSync Swift SDK 1.17.0 or later.
import Auth
import PowerSync
import Supabase
import SwiftUI
// Signs users in with Supabase Auth and gives the SDK their access token. Connect with:
// try await db.connect(endpoint: authenticator.powerSyncEndpoint, authenticator: authenticator, options: ConnectOptions())
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
@Observable
@MainActor // _session is mutable, limiting to the MainActor satisfies Sendable constraints
final class SupabaseAuthenticator: PowerSync.Authenticator {
let powerSyncEndpoint: String = Secrets.powerSyncEndpoint
let client: SupabaseClient = .init(
supabaseURL: Secrets.supabaseURL,
supabaseKey: Secrets.supabaseAnonKey,
)
private(set) var session: Session?
@ObservationIgnored
private var cachedToken: String?
@ObservationIgnored
private var observeAuthStateChangesTask: Task<Void, Never>?
init() {
session = client.auth.currentSession
observeAuthStateChangesTask = Task { [weak self, client] in
for await (event, session) in client.auth.authStateChanges {
guard [.initialSession, .signedIn, .signedOut, .tokenRefreshed].contains(event) else { continue }
guard let self else { return }
self.session = session
self.cachedToken = nil // A new session has a new token.
}
}
}
var currentUserID: String {
guard let id = session?.user.id else {
preconditionFailure("Required session.")
}
return id.uuidString.lowercased()
}
func getStorageBucket() -> StorageFileApi? {
guard let bucket = Secrets.supabaseStorageBucket else {
return nil
}
return client.storage.from(bucket)
}
/// Returns the Supabase access token for sync, cached until the SDK calls invalidateCredentials().
/// After invalidateCredentials() clears it, `client.auth.session` returns a valid session, because supabase-swift
/// refreshes the session when it expires within 30 seconds.
func resolveCredentials() async throws -> String {
if let cachedToken {
return cachedToken
}
session = try await client.auth.session
if session == nil {
throw AuthError.sessionMissing
}
let token = session!.accessToken
cachedToken = token
return token
}
/// Called by the SDK before the token expires and when the PowerSync Service rejects it.
func invalidateCredentials() async {
cachedToken = nil
}
deinit {
observeAuthStateChangesTask?.cancel()
}
}
2
Add Uploads
SupabaseUploader.swift
// Requires PowerSync Swift SDK 1.17.0 or later.
import AnyCodable
import PowerSync
import Supabase
private enum PostgresFatalCodes {
/// Postgres Response codes that we cannot recover from by retrying.
static let fatalResponseCodes: [String] = [
// Class 22 — Data Exception
// Examples include data type mismatch.
"22...",
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
"23...",
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
"42501",
]
static func isFatalError(_ code: String) -> Bool {
return fatalResponseCodes.contains { pattern in
code.range(of: pattern, options: [.regularExpression]) != nil
}
}
static func extractErrorCode(from error: any Error) -> String? {
// Look for code: Optional("XXXXX") pattern
let errorString = String(describing: error)
if let range = errorString.range(of: "code: Optional\\(\"([^\"]+)\"\\)", options: .regularExpression),
let codeRange = errorString[range].range(of: "\"([^\"]+)\"", options: .regularExpression)
{
// Extract just the code from within the quotes
let code = errorString[codeRange].dropFirst().dropLast()
return String(code)
}
return nil
}
}
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// Pass it the Supabase client from your SupabaseAuthenticator, and connect with:
// try await db.connect(
// endpoint: authenticator.powerSyncEndpoint,
// authenticator: authenticator,
// mutationUploader: SupabaseUploader(client: authenticator.client).upload,
// options: ConnectOptions()
// )
final class SupabaseUploader: Sendable {
private let client: SupabaseClient
init(client: SupabaseClient) {
self.client = client
}
/// Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay.
func upload(database: PowerSyncDatabaseProtocol) async throws {
guard let transaction = try await database.getNextCrudTransaction() else { return }
var lastEntry: CrudEntry?
do {
for entry in transaction.crud {
lastEntry = entry
let tableName = entry.table
let table = client.from(tableName)
switch entry.op {
case .put:
var data = entry.opData ?? [:]
data["id"] = entry.id
try await table.upsert(data).execute()
case .patch:
guard let opData = entry.opData else { continue }
try await table.update(opData).eq("id", value: entry.id).execute()
case .delete:
try await table.delete().eq("id", value: entry.id).execute()
}
}
try await transaction.complete()
} catch {
if let errorCode = PostgresFatalCodes.extractErrorCode(from: error),
PostgresFatalCodes.isFatalError(errorCode)
{
/// Instead of blocking the queue with these errors,
/// discard the (rest of the) transaction.
///
/// Note that these errors typically indicate a bug in the application.
/// If protecting against data loss is important, save the failing records
/// elsewhere instead of discarding, and/or notify the user.
print("Data upload error: \(error)")
print("Discarding entry: \(lastEntry!)")
try await transaction.complete()
return
}
print("Data upload error - retrying last entry: \(lastEntry!), \(error)")
throw error
}
}
}
1
Connect for Downloads
SupabaseAuthenticator.cs
// Requires PowerSync.Common 1.0.1 or later.
namespace CommandLine;
using CommandLine.Utils;
using PowerSync.Common.Client.Connection;
using Supabase;
using Supabase.Gotrue;
// Signs users in with Supabase Auth and gives the SDK their access token. Connect with:
// await db.Connect(config.PowerSyncUrl, authenticator, null);
// To upload local writes, also pass your mutation uploader:
// https://docs.powersync.com/configuration/app-backend/client-side-integration#mutation-uploader
public class SupabaseAuthenticator : IAuthenticator
{
private readonly Supabase.Client _supabase;
private Session? _currentSession;
private string? _cachedToken;
public Session? CurrentSession
{
get => _currentSession;
set
{
_currentSession = value;
if (_currentSession?.User?.Id != null)
{
UserId = _currentSession.User.Id;
}
}
}
public string UserId { get; private set; } = "";
public bool Ready { get; private set; }
/// <summary>The Supabase client that the session belongs to. Pass it to SupabaseUploader.</summary>
public Supabase.Client Client => _supabase;
public SupabaseAuthenticator(Config config)
{
_supabase = new Supabase.Client(config.SupabaseUrl, config.SupabaseAnonKey, new SupabaseOptions
{
AutoConnectRealtime = true
});
_ = _supabase.InitializeAsync();
}
public async Task Login(string email, string password)
{
var response = await _supabase.Auth.SignInWithPassword(email, password);
if (response?.User == null || response.AccessToken == null)
{
throw new Exception("Login failed.");
}
CurrentSession = response;
_cachedToken = null; // A new session has a new token.
}
/// <summary>
/// Returns the Supabase access token for sync, cached until the SDK calls InvalidateCredentials().
///
/// After InvalidateCredentials() clears the cache, this returns a valid token. The Supabase client refreshes
/// the session in the background, but CurrentSession only returns the stored session and never refreshes it.
/// If that background refresh hasn't run, for example because the app was suspended or offline, the stored
/// token can be expired, so it is refreshed here first.
/// </summary>
public async Task<string> ResolveCredentials()
{
if (_cachedToken != null)
{
return _cachedToken;
}
var session = _supabase.Auth.CurrentSession;
if (session?.AccessToken == null)
{
throw new InvalidOperationException("Not signed in to Supabase");
}
if (session.CreatedAt.AddSeconds(session.ExpiresIn) <= DateTime.UtcNow.AddMinutes(1))
{
session = await _supabase.Auth.RefreshSession();
if (session?.AccessToken == null)
{
throw new InvalidOperationException("Could not refresh the Supabase session");
}
}
return _cachedToken = session.AccessToken;
}
/// <summary>
/// Called by the SDK before the token expires and when the PowerSync Service rejects it.
/// </summary>
public void InvalidateCredentials()
{
_cachedToken = null;
}
}
2
Add Uploads
SupabaseUploader.cs
// Requires PowerSync.Common 1.0.1 or later.
namespace CommandLine;
using System.Text.RegularExpressions;
using CommandLine.Helpers;
using CommandLine.Models.Supabase;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
using PowerSync.Common.DB.Crud;
using Supabase.Postgrest.Exceptions;
using Supabase.Postgrest.Interfaces;
// Uploads local writes to Supabase through PostgREST, as the signed-in user, so your RLS policies apply.
// Pass it the Supabase client from your SupabaseAuthenticator, and connect with:
// await db.Connect(config.PowerSyncUrl, authenticator, new SupabaseUploader(authenticator.Client));
public class SupabaseUploader(Supabase.Client supabase) : IMutationUploader
{
/// <summary>
/// Postgres error codes that a retry can never fix, so the transaction is discarded
/// instead of being retried forever.
/// </summary>
private static readonly Regex[] FatalResponseCodes =
[
// Class 22 — Data Exception
// Examples include data type mismatch.
new Regex("^22...$"),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new Regex("^23...$"),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new Regex("^42501$")
];
private readonly Supabase.Client _supabase = supabase;
public async Task UploadMutations(IPowerSyncDatabase database)
{
var transaction = await database.GetNextCrudTransaction();
if (transaction == null) return;
CrudEntry? lastOp = null;
try
{
foreach (var op in transaction.Crud)
{
lastOp = op;
switch (op.Op)
{
case UpdateType.PUT:
if (op.Table.ToLower().Trim() == "lists")
{
var model = JsonConvert.DeserializeObject<List>(JsonConvert.SerializeObject(op.OpData)) ?? throw new InvalidOperationException("Model is null.");
model.Id = op.Id;
await _supabase.From<List>().Upsert(model);
}
else if (op.Table.ToLower().Trim() == "todos")
{
var model = JsonConvert.DeserializeObject<Todo>(JsonConvert.SerializeObject(op.OpData)) ?? throw new InvalidOperationException("Model is null.");
model.Id = op.Id;
await _supabase.From<Todo>().Upsert(model);
}
break;
case UpdateType.PATCH:
if (op.OpData is null || op.OpData.Count == 0)
{
Console.WriteLine("PATCH skipped: No data to update.");
break;
}
if (op.Table.ToLower().Trim() == "lists")
{
// Create an update query for the 'List' table where the 'Id' matches 'op.Id'
IPostgrestTable<List> updateQuery = _supabase
.From<List>()
.Where(x => x.Id == op.Id);
// Loop through each key-value pair in the operation data (op.OpData) to apply updates dynamically
foreach (var kvp in op.OpData)
{
// Apply the "SET" operation for each key-value pair.
// The key represents the JSON property name and the value is the new value to be set
updateQuery = SupabasePatchHelper.ApplySet(updateQuery, kvp.Key, kvp.Value);
}
_ = await updateQuery.Update();
}
else if (op.Table.ToLower().Trim() == "todos")
{
// Create an update query for the 'Todo' table where the 'Id' matches 'op.Id'
IPostgrestTable<Todo> updateQuery = _supabase
.From<Todo>()
.Where(x => x.Id == op.Id);
// Loop through each key-value pair in the operation data (op.OpData) to apply updates dynamically
foreach (var kvp in op.OpData)
{
// Apply the "SET" operation for each key-value pair.
// The key represents the JSON property name and the value is the new value to be set
updateQuery = SupabasePatchHelper.ApplySet(updateQuery, kvp.Key, kvp.Value);
}
_ = await updateQuery.Update();
}
break;
case UpdateType.DELETE:
if (op.Table.ToLower().Trim() == "lists")
{
await _supabase
.From<List>()
.Where(x => x.Id == op.Id)
.Delete();
}
else if (op.Table.ToLower().Trim() == "todos")
{
await _supabase
.From<Todo>()
.Where(x => x.Id == op.Id)
.Delete();
}
break;
default:
throw new InvalidOperationException("Unknown operation type.");
}
}
await transaction.Complete();
}
catch (PostgrestException ex)
{
var errorCode = PostgresErrorCode(ex);
if (errorCode != null && FatalResponseCodes.Any(pattern => pattern.IsMatch(errorCode)))
{
// Instead of blocking the queue with these errors,
// discard the (rest of the) transaction.
//
// Note that these errors typically indicate a bug in the application.
// If protecting against data loss is important, save the failing records
// elsewhere instead of discarding, and/or notify the user.
Console.WriteLine($"Data upload error - discarding {lastOp}: {ex.Message}");
await transaction.Complete();
return;
}
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
Console.WriteLine($"Error during upload: {ex.Message}");
throw;
}
}
/// <summary>
/// Reads the Postgres error code from a PostgREST error response. PostgrestException does not
/// expose the code directly, so it is read from the response body.
/// </summary>
private static string? PostgresErrorCode(PostgrestException exception)
{
if (string.IsNullOrWhiteSpace(exception.Content))
{
return null;
}
try
{
return JObject.Parse(exception.Content!)["code"]?.ToString();
}
catch (JsonReaderException)
{
return null;
}
}
}