JS Web

Full SDK reference for using PowerSync in JavaScript Web clients

SDK Features

  • Provides real-time streaming of database changes.

  • Offers direct access to the SQLite database, enabling the use of SQL on both client and server sides.

  • Operations are asynchronous by default, ensuring the user interface remains unblocked.

  • Enables subscription to queries for receiving live updates.

  • Eliminates the need for client-side database migrations as these are managed automatically.

  • Allows using PowerSync between multiple tabs

Installation

See the SDK's README for installation instructions.

Some peer dependencies are required.

See the Readme for the necessary peer dependencies that need to be installed.

This SDK connects to a PowerSync instance via HTTP streams (enabled by default) or WebSocket.

  • When connecting via WebSocket, a polyfill is also required.

  • See the Developer Notes section below for details about connecting with either method.

Getting Started

Before implementing the PowerSync SDK in your project, make sure you have completed these steps:

1. Define the Schema

The first step is defining the schema for the local SQLite database. This will be provided as a schema parameter to the WASQLitePowerSyncDatabaseOpenFactory class.

This schema represents a "view" of the downloaded data. No migrations are required — the schema is applied directly when the PowerSync database is constructed.

Generate schema automatically

In the dashboard, the schema can be generated based off your sync rules by right-clicking on an instance and selecting Generate client-side schema.

Similar functionality exists in the CLI.

The types available are text, integer and real. These should map directly to the values produced by the Sync Rules. If a value doesn't match, it is cast automatically. For details on how Postgres types are mapped to the types below, see the section on Types in the Sync Rules documentation.

Example:

// library/powersync/AppSchema.ts
import {
  Column,
  ColumnType,
  Index,
  IndexedColumn,
  Schema,
  Table
} from '@powersync/web';

export const AppSchema = new Schema([
  new Table({
    name: 'todos',
    columns: [
      new Column({ name: 'list_id', type: ColumnType.TEXT }),
      new Column({ name: 'created_at', type: ColumnType.TEXT }),
      new Column({ name: 'completed_at', type: ColumnType.TEXT }),
      new Column({ name: 'description', type: ColumnType.TEXT }),
      new Column({ name: 'completed', type: ColumnType.INTEGER }),
      new Column({ name: 'created_by', type: ColumnType.TEXT }),
      new Column({ name: 'completed_by', type: ColumnType.TEXT })
    ],
    // Index to allow efficient lookup within a list
    indexes: [new Index({ name: 'list', columns: [new IndexedColumn({ name: 'list_id' })] })]
  }),
  new Table({
    name: 'lists',
    columns: [
      new Column({ name: 'created_at', type: ColumnType.TEXT }),
      new Column({ name: 'name', type: ColumnType.TEXT }),
      new Column({ name: 'owner_id', type: ColumnType.TEXT })
    ]
  })
]);

Note: No need to declare a primary key id column, as PowerSync will automatically create this.

2. Instantiate the PowerSync Database

Next, you need to instantiate the PowerSync database — this is the core managed database.

Its primary functions are to record all changes in the local database, whether online or offline. In addition, it automatically uploads changes to your app backend when connected.

To instantiate PowerSyncDatabase, inject the Schema you defined in the previous step and a file path — it's important to only instantiate one instance of PowerSyncDatabase per file.

Example:

import { WASQLitePowerSyncDatabaseOpenFactory } from '@powersync/web';
import { Connector } from './Connector';
import { AppSchema } from './Schema';

const factory = new WASQLitePowerSyncDatabaseOpenFactory({
  schema: AppSchema, // The schema you defined in the previous step
  dbFilename: 'my_app_db.sqlite' // Inject a file path to the local SQLite DB — it's important to only instantiate one instance per file. 
  //location: 'optional location directory to DB file'
});

export const PowerSync = factory.getInstance();

Once you've instantiated your PowerSync database, you will need to call the connect() method to activate it.

export const setupPowerSync = async () => {
  const connector = new Connector(); // Uses the backend connector that will be created in the next section
  await PowerSync.init();
  await PowerSync.connect(connector);
};

3. Integrate with your Backend

The PowerSync backend connector provides the connection between your application backend and the PowerSync client-slide managed SQLite database.

It is used to:

  1. Retrieve an auth token to connect to the PowerSync instance.

  2. Apply local changes on your backend application server (and from there, to Postgres)

Accordingly, the connector must implement two methods:

  1. PowerSyncBackendConnector.fetchCredentials - This is called every couple of minutes and is used to obtain credentials for your app backend API. -> See Authentication Setup for instructions on how the credentials should be generated.

  2. PowerSyncBackendConnector.uploadData - Use this to upload client-side changes to your app backend.

    -> See Writing Client Changes for considerations on the app backend implementation.

Example:

import { UpdateType} from '@powersync/web';

/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
  // Class 22 — Data Exception
  // Examples include data type mismatch.
  new RegExp('^22...$'),
  // Class 23 — Integrity Constraint Violation.
  // Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
  new RegExp('^23...$'),
  // INSUFFICIENT PRIVILEGE - typically a row-level security violation
  new RegExp('^42501$')
];

export class Connector {

    constructor() {
        // Setup a connection to your server for uploads
        this.serverConnectionClient = TODO; 
    }

    async fetchCredentials() {
        // Implement fetchCredentials to obtain a JWT from your authentication service.
        // See https://docs.powersync.com/usage/installation/authentication-setup
        // If you're using Supabase or Firebase, you can re-use the JWT from those clients, see
        // - https://docs.powersync.com/usage/installation/authentication-setup/supabase-auth
        // - https://docs.powersync.com/usage/installation/authentication-setup/firebase-auth
        return {
            endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', 
            token: 'An authentication token' // Use a development token (see Authentication Setup) to get up and running quickly
        };
    }

    async uploadData(database) {
    // Implement uploadData to send local changes to your backend service.
    // You can omit this method if you only want to sync data from the database to the client
    // see https://docs.powersync.com/usage/installation/app-backend-setup/writing-client-changes
        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 (let op of transaction.crud) {
            lastOp = op;
            // Have your server connection setup before uploading
            const table = this.serverConnectionClient.from(op.table);
            switch (op.op) {
            case UpdateType.PUT:
                const record = { ...op.opData, id: op.id };
                const { error } = await table.upsert(record);
                break;
            case UpdateType.PATCH:
                await table.update(op.opData).eq('id', op.id);
                break;
            case UpdateType.DELETE:
                await table.delete().eq('id', op.id);
                break;
            }
        }

        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;
        }
        }
    }
}

Using PowerSync: CRUD functions

Once the PowerSync instance is configured you can start using the SQLite DB functions.

The most commonly used CRUD functions to interact with your SQLite data are:

Fetching a Single Item

The get method executes a read-only (SELECT) query and returns a single result. It throws an exception if no result is found. Use getOptional to return a single optional result (returns null if no result is found).

// TodoItemWidget.jsx
import React, { useState, useEffect } from 'react';

export const TodoItemWidget = ({id}) => {
    const [todoItem, setTodoItem] = useState([]);
    const [error, setError] = useState([]);

    useEffect(() => {
        // .get returns the first item of the result. Throws an exception if no result is found.
        PowerSync.get('SELECT * from todos WHERE id = ?', [id])
          .then(setTodoItem)
          .catch(ex => setError(ex.message))
    }, [id]);

    return <span>{error || (todoItem && todoItem.description)}</span>
}

Querying Items (PowerSync.getAll)

The getAll method returns a set of rows from a table.

// ListsWidget.jsx
import React, { useState, useEffect } from 'react';

export const ListsWidget = () => {
    const [lists, setLists] = useState([]);

    useEffect(() => {
        PowerSync.getAll('SELECT * from lists').then(setLists);
    }, []);

    return (
        <ul>
            {lists.map(list => (
                <li key={list.id}>
                    {list.name}
                </li>
            ))}
        </ul>
    );
}

Watching Queries (PowerSync.watch)

The watch method executes a read query whenever a change to a dependent table is made.

// ListsWidget.jsx
import React, { useState, useEffect, useRef } from 'react';

export const ListsWidget = () => {
    const [lists, setLists] = useState([]);

    useEffect(() => {
        const abortController = new AbortController();
        
        (async () => {
            for await (const update of PowerSync.watch('SELECT * from lists', [], { signal: abortController.signal })) {
                setLists(update);
            }
        })();

        return () => {
            abortController.abort();
        };
    }, []);

    return (
        <ul>
            {lists.map(list => (
                <li key={list.id}>
                    {list.name}
                </li>
            ))}
        </ul>
    );
}

Mutations (PowerSync.execute)

The execute method can be used for executing single SQLite write statements.

// ListsWidget.jsx
import React, { useState } from 'react';

export const ListsWidget = () => {
    const [lists, setLists] = useState([]);

    return (
        <div>
            <ul>
                {lists.map(list => (
                    <li key={list.id}>
                        {list.name}
                        <button onClick={async () => {
                            try {
                                await PowerSync.execute(`DELETE FROM lists WHERE id = ?`, [list.id]);
                                // Watched queries should automatically reload after mutation
                            } catch (ex) {
                                alert('Error: ' + ex.message);
                            }
                        }}>
                            Delete
                        </button>
                    </li>
                ))}
            </ul>
            <button onClick={async () => {
                try {
                    await PowerSync.execute('INSERT INTO lists (id, created_at, name, owner_id) VALUES (uuid(), datetime(), ?, ?) RETURNING *', [
                        'A list name',
                        "[The user's uuid]"
                    ]);
                    // Watched queries should automatically reload after mutation
                } catch (ex) {
                    alert('Error: ' + ex.message);
                }
            }}>
                Create List
            </button>
        </div>
    );
}

Additional Usage Examples

See Usage Examples for further examples of the SDK.

Developer Notes

Connecting via HTTP Streams or WebSocket

This SDK connects to a PowerSync instance and streams sync commands via HTTP streams (enabled by default) or WebSockets.

The WebSocket implementation uses reactive socket streams from the cross-platform RSocket library. This allows the client to request commands from the server after processing existing events, alleviating any back-pressure build-up of commands. Sync commands are transmitted as BSON (binary) documents.

Benefits of using the WebSocket Method

  • BLOB column support will be added on top of the WebSocket implementation (the HTTP streaming method will not support this).

Selecting Connection Method

The PowerSyncDatabase client's connect method now supports options which can be used to select the active connection method. These options are not required, as HTTP is used by default.

// For HTTP
powerSync.connect(connector)

// For WebSockets
powerSync.connect(connector, { connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET });

ORM Support

See JavaScript ORM Support for details.

Source Code

To access the source code for this SDK, refer to packages/web in the powersync-js repo on GitHub.

Last updated