|
| 1 | +--- |
| 2 | +title: "Node.js client (alpha)" |
| 3 | +description: "SDK reference for using PowerSync in Node.js clients." |
| 4 | +sidebarTitle: Overview |
| 5 | +--- |
| 6 | + |
| 7 | +<Note> |
| 8 | + This page describes the PowerSync _client_ SDK for Node.js. |
| 9 | + If you're interested in using PowerSync for your Node.js backend, no special package is required. |
| 10 | + Instead, follow our guides on [app backend setup](/installation/app-backend-setup). |
| 11 | +</Note> |
| 12 | + |
| 13 | +<CardGroup> |
| 14 | + <Card title="PowerSync SDK on NPM" icon="npm" href="https://www.npmjs.com/package/@powersync/node"> |
| 15 | + This SDK is distributed via NPM [\[External link\].](https://www.npmjs.com/package/@powersync/node) |
| 16 | + </Card> |
| 17 | + |
| 18 | + <Card title="Source Code" icon="github" href="https://github.com/powersync-ja/powersync-js/tree/main/packages/node"> |
| 19 | + Refer to packages/node in the powersync-js repo on GitHub. |
| 20 | + </Card> |
| 21 | + |
| 22 | + <Card title="API Reference" icon="book" href="https://powersync-ja.github.io/powersync-js/node-sdk"> |
| 23 | + Full API reference for the PowerSync SDK [\[External link\].](https://powersync-ja.github.io/powersync-js/node-sdk) |
| 24 | + </Card> |
| 25 | + |
| 26 | + <Card title="Example Project" icon="code" href="https://github.com/powersync-ja/powersync-js/tree/main/demos/example-node"> |
| 27 | + A small CLI app showcasing bidirectional sync. |
| 28 | + </Card> |
| 29 | +</CardGroup> |
| 30 | + |
| 31 | +## SDK Features |
| 32 | + |
| 33 | +* Provides real-time streaming of database changes. |
| 34 | +* Offers direct access to the SQLite database, enabling the use of SQL on both client and server sides. |
| 35 | +* Operations run on a background worker and are asynchronous by default, enabling concurrent queries. |
| 36 | +* Enables subscription to queries for receiving live updates. |
| 37 | +* Eliminates the need for client-side database migrations as these are managed automatically. |
| 38 | + |
| 39 | +## Quickstart |
| 40 | + |
| 41 | +To start using PowerSync in a Node client, first add the dependencies: |
| 42 | + |
| 43 | +<Tabs> |
| 44 | +<Tab title="npm"> |
| 45 | + ```bash |
| 46 | + npm install @powersync/node |
| 47 | + ``` |
| 48 | +</Tab> |
| 49 | +<Tab title="yarn"> |
| 50 | + ```bash |
| 51 | + yarn add @powersync/node |
| 52 | + ``` |
| 53 | +</Tab> |
| 54 | +<Tab title="pnpm"> |
| 55 | + ```bash |
| 56 | + pnpm install @powersync/node |
| 57 | + ``` |
| 58 | +</Tab> |
| 59 | +</Tabs> |
| 60 | + |
| 61 | +Depending on the package manager used, you might have to approve install scripts. |
| 62 | +PowerSync currently requires install scripts on the `@powersync/node` and `@powersync/better-sqlite3` packages |
| 63 | +to download native addons. |
| 64 | + |
| 65 | +Next, make sure that you have: |
| 66 | + |
| 67 | +* Signed up for a PowerSync Cloud account ([here](https://accounts.journeyapps.com/portal/powersync-signup?s=docs)) or [self-host PowerSync](/self-hosting/getting-started). |
| 68 | +* [Configured your backend database](/installation/database-setup) and connected it to your PowerSync instance. |
| 69 | + |
| 70 | +### 1. Define the schema |
| 71 | + |
| 72 | +The first step is defining the schema for the local SQLite database. |
| 73 | + |
| 74 | +This schema represents a "view" of the downloaded data. No migrations are required — the schema is applied directly when the local PowerSync database is constructed (as we'll show in the next step). |
| 75 | +You can use [this example](https://github.com/powersync-ja/powersync-js/blob/e5a57a539150f4bc174e109d3898b6e533de272f/demos/example-node/src/powersync.ts#L47-L77) as a reference when defining your schema. |
| 76 | + |
| 77 | +<Info> |
| 78 | + **Generate schema automatically** |
| 79 | + |
| 80 | + In the [dashboard](/usage/tools/powersync-dashboard), the schema can be generated based off your sync rules by right-clicking on an instance and selecting **Generate client-side schema**. |
| 81 | + Select JavaScript and replace the suggested import with `@powersync/node`. |
| 82 | + |
| 83 | + Similar functionality exists in the [CLI](/usage/tools/cli). |
| 84 | +</Info> |
| 85 | + |
| 86 | +### 2. Instantiate the PowerSync Database |
| 87 | + |
| 88 | +Next, you need to instantiate the PowerSync database — this is the core managed database. |
| 89 | + |
| 90 | +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. |
| 91 | + |
| 92 | +**Example**: |
| 93 | + |
| 94 | +```js |
| 95 | +import { PowerSyncDatabase } from '@powersync/node'; |
| 96 | +import { Connector } from './Connector'; |
| 97 | +import { AppSchema } from './Schema'; |
| 98 | + |
| 99 | +export const db = new PowerSyncDatabase({ |
| 100 | + // The schema you defined in the previous step |
| 101 | + schema: AppSchema, |
| 102 | + database: { |
| 103 | + // Filename for the SQLite database — it's important to only instantiate one instance per file. |
| 104 | + dbFilename: 'powersync.db', |
| 105 | + // Optional. Directory where the database file is located.' |
| 106 | + // dbLocation: 'path/to/directory' |
| 107 | + }, |
| 108 | +}); |
| 109 | +``` |
| 110 | + |
| 111 | +### 3. Integrate with your Backend |
| 112 | + |
| 113 | +The PowerSync backend connector provides the connection between your application backend and the PowerSync client-slide managed SQLite database. |
| 114 | + |
| 115 | +It is used to: |
| 116 | + |
| 117 | +1. Retrieve an auth token to connect to the PowerSync instance. |
| 118 | +2. Apply local changes on your backend application server (and from there, to Postgres) |
| 119 | + |
| 120 | +Accordingly, the connector must implement two methods: |
| 121 | + |
| 122 | +1. [PowerSyncBackendConnector.fetchCredentials](https://github.com/powersync-ja/powersync-js/blob/ed5bb49b5a1dc579050304fab847feb8d09b45c7/packages/common/src/client/connection/PowerSyncBackendConnector.ts#L16) - This is called every couple of minutes and is used to obtain credentials for your app backend API. -> See [Authentication Setup](/installation/authentication-setup) for instructions on how the credentials should be generated. |
| 123 | +2. [PowerSyncBackendConnector.uploadData](https://github.com/powersync-ja/powersync-js/blob/ed5bb49b5a1dc579050304fab847feb8d09b45c7/packages/common/src/client/connection/PowerSyncBackendConnector.ts#L24) - Use this to upload client-side changes to your app backend. |
| 124 | + -> See [Writing Client Changes](/installation/app-backend-setup/writing-client-changes) for considerations on the app backend implementation. |
| 125 | + |
| 126 | +**Example**: |
| 127 | + |
| 128 | +```js |
| 129 | +import { UpdateType } from '@powersync/node'; |
| 130 | + |
| 131 | +export class Connector implements PowerSyncBackendConnector { |
| 132 | + constructor() { |
| 133 | + // Setup a connection to your server for uploads |
| 134 | + this.serverConnectionClient = TODO; |
| 135 | + } |
| 136 | + |
| 137 | + async fetchCredentials() { |
| 138 | + // Implement fetchCredentials to obtain a JWT from your authentication service. |
| 139 | + // See https://docs.powersync.com/installation/authentication-setup |
| 140 | + // If you're using Supabase or Firebase, you can re-use the JWT from those clients, see |
| 141 | + // - https://docs.powersync.com/installation/authentication-setup/supabase-auth |
| 142 | + // - https://docs.powersync.com/installation/authentication-setup/firebase-auth |
| 143 | + return { |
| 144 | + endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', |
| 145 | + // Use a development token (see Authentication Setup https://docs.powersync.com/installation/authentication-setup/development-tokens) to get up and running quickly |
| 146 | + token: 'An authentication token' |
| 147 | + }; |
| 148 | + } |
| 149 | + |
| 150 | + async uploadData(database) { |
| 151 | + // Implement uploadData to send local changes to your backend service. |
| 152 | + // You can omit this method if you only want to sync data from the database to the client |
| 153 | + |
| 154 | + // See example implementation here: https://docs.powersync.com/client-sdk-references/javascript-web#3-integrate-with-your-backend |
| 155 | + } |
| 156 | +} |
| 157 | +``` |
| 158 | + |
| 159 | +With your database instantiated and your connector ready, call `connect` to start the synchronization process: |
| 160 | + |
| 161 | +```js |
| 162 | +await db.connect(new Connector()); |
| 163 | +await db.waitForFirstSync(); // Optional, to wait for a complete snapshot of data to be available |
| 164 | +``` |
| 165 | + |
| 166 | +## Usage |
| 167 | + |
| 168 | +After connecting the client database, it is ready to be used. The API to run queries and updates is identical to our |
| 169 | +[web SDK](/client-sdk-references/javascript-web#using-powersync%3A-crud-functions): |
| 170 | + |
| 171 | +```js |
| 172 | +// Use db.get() to fetch a single row: |
| 173 | +console.log(await db.get('SELECT powersync_rs_version();')); |
| 174 | + |
| 175 | +// Or db.all() to fetch all: |
| 176 | +console.log(await db.all('SELECT * FROM lists;')); |
| 177 | + |
| 178 | +// Use db.watch() to watch queries for changes: |
| 179 | +const watchLists = async () => { |
| 180 | + for await (const rows of db.watch('SELECT * FROM lists;')) { |
| 181 | + console.log('Has todo lists', rows.rows!._array); |
| 182 | + } |
| 183 | +}; |
| 184 | +watchLists(); |
| 185 | + |
| 186 | +// And db.execute for inserts, updates and deletes: |
| 187 | +await db.execute( |
| 188 | + "INSERT INTO lists (id, created_at, name, owner_id) VALUEs (uuid(), datetime('now'), ?, uuid());", |
| 189 | + ['My new list'] |
| 190 | +); |
| 191 | +``` |
| 192 | + |
| 193 | +PowerSync runs queries asynchronously on a background pool of workers and automatically configures WAL to |
| 194 | +allow a writer and multiple readers to operate in parallel. |
0 commit comments