fetchCredentials() and uploadData(). The Rust SDK splits these into an Authenticator and a MutationUploader. Copy the example for your SDK into your app, then replace the placeholders.
Custom Backend
Your app uploads writes to its own backend, or to the reference write endpoint.
Supabase
Your source database is Supabase and your app uses Supabase Auth.
Custom Backend
Use these examples if your app uploads writes to its own backend. By default, they call the reference write endpoint,POST /api/data. If your API’s request or response format differs, either change the request and response handling in uploadData() to match your API, or use the prompt for your coding agent to generate an uploadData() for it.
Each example sends the same JWT to your PowerSync instance and to your write endpoint. Replace the token placeholder with a token from your auth provider. See Authentication Setup.
- JavaScript
- TypeScript
- React Native
- Dart
- Kotlin
- Swift
- .NET
- Rust
PowerSyncConnector.js
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts
// 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;
export class MyBackendConnector {
constructor() {
this.authToken = null;
}
async fetchCredentials() {
return {
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
token: await this.getAuthToken()
};
}
/**
* 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 uploadData(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.authToken = null; // 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';
}
/**
* Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
* The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
* return `this.fetchAuthToken()` directly instead.
*/
async getAuthToken() {
if (!this.authToken) {
this.authToken = await this.fetchAuthToken();
}
return this.authToken;
}
/**
* 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 use a development token with the write endpoint, see
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
*/
async fetchAuthToken() {
return 'An authentication token';
}
/**
* 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-api.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.getAuthToken())
},
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 {}
PowerSyncConnector.ts
import type { AbstractPowerSyncDatabase, CrudTransaction, PowerSyncBackendConnector } from '@powersync/web';
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts
/** 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;
export class MyBackendConnector implements PowerSyncBackendConnector {
private authToken: string | null = null;
async fetchCredentials() {
return {
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
token: await this.getAuthToken()
};
}
/**
* 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 uploadData(database: AbstractPowerSyncDatabase): Promise<void> {
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.authToken = null; // 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';
}
/**
* Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
* The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
* return `this.fetchAuthToken()` directly instead.
*/
private async getAuthToken(): Promise<string> {
if (!this.authToken) {
this.authToken = await this.fetchAuthToken();
}
return this.authToken;
}
/**
* 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 use a development token with the write endpoint, see
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
*/
private async fetchAuthToken(): Promise<string> {
return 'An authentication token';
}
/** 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.getAuthToken()}`
},
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-api.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 {}
PowerSyncConnector.ts
import type { AbstractPowerSyncDatabase, CrudTransaction, PowerSyncBackendConnector } from '@powersync/react-native';
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts
/** 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;
export class MyBackendConnector implements PowerSyncBackendConnector {
private authToken: string | null = null;
async fetchCredentials() {
return {
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
token: await this.getAuthToken()
};
}
/**
* 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 uploadData(database: AbstractPowerSyncDatabase): Promise<void> {
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.authToken = null; // 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';
}
/**
* Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
* The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
* return `this.fetchAuthToken()` directly instead.
*/
private async getAuthToken(): Promise<string> {
if (!this.authToken) {
this.authToken = await this.fetchAuthToken();
}
return this.authToken;
}
/**
* 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 use a development token with the write endpoint, see
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
*/
private async fetchAuthToken(): Promise<string> {
return 'An authentication token';
}
/** 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.getAuthToken()}`
},
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-api.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 {}
lib/powersync.dart
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts
import 'dart:convert';
import 'package:http/http.dart' as http; // Add the http package: https://pub.dev/packages/http
import 'package:powersync/powersync.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);
class MyBackendConnector extends PowerSyncBackendConnector {
String? _authToken;
@override
Future<PowerSyncCredentials?> fetchCredentials() async {
return PowerSyncCredentials(
endpoint: '[Your PowerSync instance URL or self-hosted endpoint]',
token: await _getAuthToken(),
);
}
/// 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> uploadData(PowerSyncDatabase database) 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.
_authToken = null;
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;
}
/// Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
/// The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
/// return `_fetchAuthToken()` directly instead.
Future<String> _getAuthToken() async {
return _authToken ??= await _fetchAuthToken();
}
/// 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 use a development token with the write endpoint, see
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
Future<String> _fetchAuthToken() async {
return 'An authentication token';
}
/// 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-api.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',
'Authorization': 'Bearer ${await _getAuthToken()}',
},
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;
}
PowerSync.kt
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.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.PowerSyncBackendConnector
import com.powersync.connectors.PowerSyncCredentials
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
open class MyBackendConnector(
private val httpClient: HttpClient = HttpClient(),
) : PowerSyncBackendConnector() {
private var authToken: String? = null
override suspend fun fetchCredentials(): PowerSyncCredentials? {
return PowerSyncCredentials(
endpoint = "[Your PowerSync instance URL or self-hosted endpoint]",
token = getAuthToken(),
)
}
/**
* 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 uploadData(database: PowerSyncDatabase) {
val transaction = database.getNextCrudTransaction() ?: return
val result = try {
postTransaction(transaction)
} catch (e: AuthenticationException) {
// Fetch a new token before the next attempt.
authToken = null
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
}
/**
* Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
* The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
* return fetchAuthToken() directly instead.
*/
private suspend fun getAuthToken(): String = authToken ?: fetchAuthToken().also { authToken = it }
/**
* 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 use a development token with the write endpoint, see
* https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
*/
private suspend fun fetchAuthToken(): String = "An authentication token"
/**
* 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-api.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(getAuthToken())
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
PowerSyncConnector.swift
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 uploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.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
/// An actor, because the SDK requires a Sendable connector and this one caches a token.
actor MyBackendConnector: PowerSyncBackendConnectorProtocol {
private var authToken: String?
func fetchCredentials() async throws -> PowerSyncCredentials? {
return PowerSyncCredentials(
endpoint: "[Your PowerSync instance URL or self-hosted endpoint]",
token: try await getAuthToken()
)
}
/// 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 uploadData(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.
authToken = nil
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
}
/// Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
/// The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
/// return `fetchAuthToken()` directly instead.
private func getAuthToken() async throws -> String {
if let authToken {
return authToken
}
let token = try await fetchAuthToken()
authToken = token
return token
}
/// 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 use a development token with the write endpoint, see
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
private func fetchAuthToken() async throws -> String {
return "An authentication token"
}
/// 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-api.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 getAuthToken())", 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
}
PowerSyncConnector.cs
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 UploadData() 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.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;
public class MyBackendConnector : IPowerSyncBackendConnector
{
// 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) };
private string? _authToken;
public async Task<PowerSyncCredentials?> FetchCredentials()
{
return new PowerSyncCredentials(
"[Your PowerSync instance URL or self-hosted endpoint]",
await GetAuthToken());
}
/// <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 UploadData(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.
_authToken = null;
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>
/// Returns the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
/// The token is cached until the write endpoint rejects it. If your auth provider's SDK refreshes sessions itself,
/// return FetchAuthToken() directly instead.
/// </summary>
private async Task<string> GetAuthToken()
{
return _authToken ??= await FetchAuthToken();
}
/// <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 use a development token with the write endpoint, see
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
/// </summary>
private Task<string> FetchAuthToken()
{
return Task.FromResult("An authentication token");
}
/// <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-api.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 GetAuthToken());
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);
src/connector.rs
// Uploads local writes to the PowerSync reference write endpoint, one transaction per request.
// 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 connector:
// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.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, Mutex};
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};
/// 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` for downloads and uploads.
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;
}
/// Provides the token for sync and for the write endpoint, which accepts the same JWTs as your PowerSync instance.
/// The token is cached until the PowerSync Service or the write endpoint rejects it.
#[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 use a development token with the write endpoint, see
/// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md
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)
}
/// Called by the SDK when the PowerSync Service rejects the token, and by the uploader when the write endpoint
/// rejects it. If your auth provider's SDK refreshes sessions itself, return its current token from
/// resolve_credentials() instead of caching it.
fn invalidate_credentials(&self) {
*self.token.lock().unwrap() = None;
}
}
pub struct MyMutationUploader {
db: PowerSyncDatabase,
authenticator: MyAuthenticator,
http: reqwest::Client,
}
impl MyMutationUploader {
pub fn new(db: PowerSyncDatabase, authenticator: MyAuthenticator) -> Self {
Self {
db,
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-api.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
Use these examples if your source database is Supabase and your app uses Supabase Auth. They upload writes with the Supabase client SDK, which is the PostgREST route. There is no Supabase example for Rust.- JavaScript
- TypeScript
- React Native
- Dart
- Kotlin
- Swift
- .NET
PowerSyncConnector.js
import { BaseObserver, UpdateType } from '@powersync/web';
import { createClient } 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$')
];
export class SupabaseConnector extends BaseObserver {
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, password) {
const {
data: { session },
error
} = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.updateSession(session);
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: this.config.powersyncUrl,
token: session.access_token ?? ''
};
}
async uploadData(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;
}
}
}
updateSession(session) {
this.currentSession = session;
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
PowerSyncConnector.ts
import {
BaseObserver,
UpdateType,
type CommonPowerSyncDatabase,
type CrudEntry,
type PowerSyncBackendConnector,
type PowerSyncCredentials
} from '@powersync/web';
import { Session, SupabaseClient, createClient } from '@supabase/supabase-js';
export type SupabaseConfig = {
supabaseUrl: string;
supabaseAnonKey: string;
powersyncUrl: string;
};
/// 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$')
];
export type SupabaseConnectorListener = {
initialized: () => void;
sessionStarted: (session: Session) => void;
};
export class SupabaseConnector extends BaseObserver<SupabaseConnectorListener> implements PowerSyncBackendConnector {
readonly client: SupabaseClient;
readonly config: SupabaseConfig;
ready: boolean;
currentSession: Session | 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);
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: this.config.powersyncUrl,
token: session.access_token ?? ''
} satisfies PowerSyncCredentials;
}
async uploadData(database: CommonPowerSyncDatabase): Promise<void> {
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;
}
}
}
updateSession(session: Session | null) {
this.currentSession = session;
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
PowerSyncConnector.ts
import { UpdateType, type CommonPowerSyncDatabase, type CrudEntry, type PowerSyncBackendConnector, type PowerSyncCredentials } 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';
/// 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$')
];
export class SupabaseConnector implements PowerSyncBackendConnector {
client: SupabaseClient;
storage: SupabaseStorageAdapter;
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;
}
}
async userId() {
const {
data: { session },
} = await this.client.auth.getSession();
return session?.user.id;
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: AppConfig.powersyncUrl,
token: session.access_token ?? ''
} satisfies PowerSyncCredentials;
}
async uploadData(database: CommonPowerSyncDatabase): Promise<void> {
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;
}
}
}
}
lib/powersync.dart
// This file performs setup of the PowerSync database
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import 'package:powersync_flutter_demo/migrations/fts_setup.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import './app_config.dart';
import './models/schema.dart';
import './supabase.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$'),
];
/// Use Supabase for authentication and data upload.
class SupabaseConnector extends PowerSyncBackendConnector {
PowerSyncDatabase db;
Future<void>? _refreshFuture;
SupabaseConnector(this.db);
/// Get a Supabase token to authenticate against the PowerSync instance.
@override
Future<PowerSyncCredentials?> fetchCredentials() async {
// Wait for pending session refresh if any
await _refreshFuture;
// Use Supabase token for PowerSync
final session = Supabase.instance.client.auth.currentSession;
if (session == null) {
// Not logged in
return null;
}
// Use the access token to authenticate against PowerSync
final token = session.accessToken;
// userId and expiresAt are for debugging purposes only
final userId = session.user.id;
final expiresAt = session.expiresAt == null
? null
: DateTime.fromMillisecondsSinceEpoch(session.expiresAt! * 1000);
return PowerSyncCredentials(
endpoint: AppConfig.powersyncUrl,
token: token,
userId: userId,
expiresAt: expiresAt);
}
@override
void invalidateCredentials() {
// 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. Errors will surface as expired tokens.
_refreshFuture = Supabase.instance.client.auth
.refreshSession()
.timeout(const Duration(seconds: 5))
.then((response) => null, onError: (error) => null);
}
// Upload pending changes to Supabase.
@override
Future<void> uploadData(PowerSyncDatabase database) 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;
}
}
}
}
/// 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();
SupabaseConnector? currentConnector;
if (isLoggedIn()) {
// If the user is already logged in, connect immediately.
// Otherwise, connect once logged in.
currentConnector = SupabaseConnector(db);
db.connect(connector: currentConnector);
}
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
currentConnector = SupabaseConnector(db);
db.connect(connector: currentConnector!);
} else if (event == AuthChangeEvent.signedOut) {
// Implicit sign out - disconnect, but don't delete data
currentConnector = null;
await db.disconnect();
} else if (event == AuthChangeEvent.tokenRefreshed) {
// Supabase token refreshed - trigger token refresh for PowerSync.
currentConnector?.prefetchCredentials();
}
});
// Demo using SQLite Full-Text Search with PowerSync.
// See https://docs.powersync.com/usage-examples/full-text-search for more details
await configureFts(db);
}
/// Explicit sign out - clear database and log out.
Future<void> logout() async {
await Supabase.instance.client.auth.signOut();
await db.disconnectAndClear();
}
PowerSync.kt
package com.powersync.connector.supabase
import co.touchlab.kermit.Logger
import com.powersync.PowerSyncDatabase
import com.powersync.connectors.PowerSyncBackendConnector
import com.powersync.connectors.PowerSyncCredentials
import com.powersync.db.crud.CrudEntry
import com.powersync.db.crud.CrudTransaction
import com.powersync.db.crud.UpdateType
import com.powersync.db.runWrapped
import io.github.jan.supabase.SupabaseClient
import io.github.jan.supabase.annotations.SupabaseInternal
import io.github.jan.supabase.auth.Auth
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.providers.builtin.Email
import io.github.jan.supabase.auth.status.SessionStatus
import io.github.jan.supabase.auth.user.UserSession
import io.github.jan.supabase.createSupabaseClient
import io.github.jan.supabase.postgrest.Postgrest
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.BucketApi
import io.github.jan.supabase.storage.Storage
import io.github.jan.supabase.storage.storage
import io.ktor.client.plugins.HttpSend
import io.ktor.client.plugins.plugin
import io.ktor.client.statement.bodyAsText
import io.ktor.utils.io.InternalAPI
import kotlinx.coroutines.flow.StateFlow
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlin.toString
/**
* Get a Supabase token to authenticate against the PowerSync instance.
*/
@OptIn(SupabaseInternal::class, InternalAPI::class)
public open class SupabaseConnector(
public val supabaseClient: SupabaseClient,
public val powerSyncEndpoint: String,
private val storageBucket: String? = null,
) : PowerSyncBackendConnector() {
private val json = Json { coerceInputValues = true }
private var errorCode: String? = null
public companion object PostgresFatalCodes {
// Using Regex patterns for Postgres error codes
private val FATAL_RESPONSE_CODES =
listOf(
// Class 22 — Data Exception
"^22...".toRegex(),
// Class 23 — Integrity Constraint Violation
"^23...".toRegex(),
// INSUFFICIENT PRIVILEGE
"^42501$".toRegex(),
)
public fun isFatalError(code: String): Boolean =
FATAL_RESPONSE_CODES.any { pattern ->
pattern.matches(code)
}
}
public fun storageBucket(): BucketApi {
if (storageBucket == null) {
throw Exception("No bucket has been specified")
}
return supabaseClient.storage[storageBucket]
}
public constructor(
supabaseUrl: String,
supabaseKey: String,
powerSyncEndpoint: String,
storageBucket: String? = null,
) : this(
supabaseClient =
createSupabaseClient(supabaseUrl, supabaseKey) {
install(Auth)
install(Postgrest)
if (storageBucket != null) {
install(Storage)
}
},
powerSyncEndpoint = powerSyncEndpoint,
storageBucket = storageBucket,
)
init {
require(supabaseClient.pluginManager.getPluginOrNull(Auth) != null) { "The Auth plugin must be installed on the Supabase client" }
require(
supabaseClient.pluginManager.getPluginOrNull(Postgrest) != null,
) { "The Postgrest plugin must be installed on the Supabase client" }
// This retrieves the error code from the response
// as this is not accessible in the Supabase client RestException
// to handle fatal Postgres errors
supabaseClient.httpClient.httpClient.plugin(HttpSend).intercept { request ->
val resp = execute(request)
val response = resp.response
if (response.status.value >= 400) {
val responseText = response.bodyAsText()
try {
val error =
json.decodeFromString<Map<String, String?>>(
responseText,
)
errorCode = error["code"]
} catch (e: Exception) {
Logger.e("Failed to parse error response: $e")
}
}
resp
}
}
public suspend fun login(
email: String,
password: String,
) {
runWrapped {
supabaseClient.auth.signInWith(Email) {
this.email = email
this.password = password
}
}
}
public suspend fun signUp(
email: String,
password: String,
) {
runWrapped {
supabaseClient.auth.signUpWith(Email) {
this.email = email
this.password = password
}
}
}
public suspend fun signOut() {
runWrapped {
supabaseClient.auth.signOut()
}
}
public fun session(): UserSession? = supabaseClient.auth.currentSessionOrNull()
public val sessionStatus: StateFlow<SessionStatus> = supabaseClient.auth.sessionStatus
public suspend fun loginAnonymously() {
runWrapped {
supabaseClient.auth.signInAnonymously()
}
}
/**
* Get credentials for PowerSync.
*/
override suspend fun fetchCredentials(): PowerSyncCredentials =
runWrapped {
check(supabaseClient.auth.sessionStatus.value is SessionStatus.Authenticated) { "Supabase client is not authenticated" }
// Use Supabase token for PowerSync
val session =
supabaseClient.auth.currentSessionOrNull()
?: error("Could not fetch Supabase credentials")
check(session.user != null) { "No user data" }
PowerSyncCredentials(
endpoint = powerSyncEndpoint,
token = session.accessToken, // Use the access token to authenticate against PowerSync
)
}
/**
* Uses the PostgREST APIs to upload a given [entry] to the backend database.
*
* This method should report errors during the upload as an exception that would be caught by [uploadData].
*/
public open suspend fun uploadCrudEntry(entry: CrudEntry) {
val table = supabaseClient.from(entry.table)
when (entry.op) {
UpdateType.PUT -> {
val data =
buildMap {
put("id", JsonPrimitive(entry.id))
entry.opData?.jsonValues?.let { putAll(it) }
}
table.upsert(data)
}
UpdateType.PATCH -> {
table.update(entry.opData!!.jsonValues) {
filter {
eq("id", entry.id)
}
}
}
UpdateType.DELETE -> {
table.delete {
filter {
eq("id", entry.id)
}
}
}
}
}
/**
* Handles an error during the upload. This method can be overridden to log errors or customize error handling.
*
* By default, it discards the rest of a transaction when the error code indicates that this is a fatal postgres
* error that can't be retried. Otherwise, it rethrows the exception so that the PowerSync SDK will retry.
*
* @param tx The full [CrudTransaction] we're in the process of uploading.
* @param entry The [CrudEntry] for which an upload has failed.
* @param exception The [Exception] thrown by the Supabase client.
* @param [errorCode] The postgres error code, if any.
* @throws Exception If the upload should be retried. If this method doesn't throw, it should mark [tx] as complete
* by invoking [CrudTransaction.complete]. In that case, the local write would be lost.
*/
public open suspend fun handleError(
tx: CrudTransaction,
entry: CrudEntry,
exception: Exception,
errorCode: String?,
) {
if (errorCode != null && 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.
*/
Logger.e("Data upload error: ${exception.message}")
Logger.e("Discarding entry: $entry")
tx.complete(null)
return
}
Logger.e("Data upload error - retrying last entry: $entry, $exception")
throw exception
}
/**
* Upload local changes to the app backend (in this case Supabase).
*
* 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.
*/
override suspend fun uploadData(database: PowerSyncDatabase) {
return runWrapped {
val transaction = database.getNextCrudTransaction() ?: return@runWrapped
var lastEntry: CrudEntry? = null
try {
for (entry in transaction.crud) {
lastEntry = entry
uploadCrudEntry(entry)
}
transaction.complete(null)
} catch (e: Exception) {
if (lastEntry != null) {
handleError(transaction, lastEntry, e, errorCode)
} else {
throw e
}
}
}
}
}
PowerSyncConnector.swift
import AnyCodable
import Auth
import PowerSync
import Supabase
import SwiftUI
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
}
}
@Observable
@MainActor // _session is mutable, limiting to the MainActor satisfies Sendable constraints
final class SupabaseConnector: PowerSyncBackendConnectorProtocol {
let powerSyncEndpoint: String = Secrets.powerSyncEndpoint
let client: SupabaseClient = .init(
supabaseURL: Secrets.supabaseURL,
supabaseKey: Secrets.supabaseAnonKey,
)
private(set) var session: Session?
private var errorCode: String?
@ObservationIgnored
private var observeAuthStateChangesTask: Task<Void, Error>?
init() {
session = client.auth.currentSession
observeAuthStateChangesTask = Task { [weak self] in
guard let self = self else { return }
for await (event, session) in self.client.auth.authStateChanges {
guard [.initialSession, .signedIn, .signedOut].contains(event) else { throw AuthError.sessionMissing }
self.session = session
}
}
}
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)
}
func fetchCredentials() async throws -> PowerSyncCredentials? {
session = try await client.auth.session
if session == nil {
throw AuthError.sessionMissing
}
let token = session!.accessToken
return PowerSyncCredentials(endpoint: powerSyncEndpoint, token: token)
}
func uploadData(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
}
}
deinit {
observeAuthStateChangesTask?.cancel()
}
}
PowerSyncConnector.cs
namespace CommandLine;
using System.Text.RegularExpressions;
using CommandLine.Helpers;
using CommandLine.Models.Supabase;
using CommandLine.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
using PowerSync.Common.DB.Crud;
using Supabase;
using Supabase.Gotrue;
using Supabase.Postgrest.Exceptions;
using Supabase.Postgrest.Interfaces;
public class SupabaseConnector : IPowerSyncBackendConnector
{
/// <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;
private readonly Config _config;
private Session? _currentSession;
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; }
public SupabaseConnector(Config config)
{
_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;
}
public Task<PowerSyncCredentials?> FetchCredentials()
{
PowerSyncCredentials? credentials = null;
var sessionResponse = _supabase.Auth.CurrentSession;
if (sessionResponse?.AccessToken != null)
{
credentials = new PowerSyncCredentials(_config.PowerSyncUrl, sessionResponse.AccessToken);
}
return Task.FromResult(credentials);
}
public async Task UploadData(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;
}
}
}