Skip to main content

@powersync/nuxt

PowerSync Nuxt Module - Public API

This module provides PowerSync integration for Nuxt applications with built-in diagnostics and inspector capabilities.

Interfaces​

NuxtPowerSyncDatabase​

Extends​

  • CommonPowerSyncDatabase

Properties​

PropertyModifierTypeDescriptionInherited from
closedreadonlybooleanReturns true if the connection is closed.CommonPowerSyncDatabase.closed
currentStatusreadonlySyncStatusCurrent connection status.CommonPowerSyncDatabase.currentStatus
executepublic<T>(query, params?) => Promise<QueryResult<T>>Execute a SQL write (INSERT/UPDATE/DELETE) query and optionally return results. When using the default client-side JSON-based view system, the returned result's rowsAffected may be 0 for successful UPDATE and DELETE statements. Use a RETURNING clause and inspect result.rows when you need to confirm which rows changed.CommonPowerSyncDatabase.execute
executeBatchpublic(query, params?) => Promise<QueryResult<never>>Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set and optionally return results. This is faster than executing separately with each parameter set.CommonPowerSyncDatabase.executeBatch
executeRawpublic(query, params?) => Promise<RawQueryResult>Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing. This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.CommonPowerSyncDatabase.executeRaw
loggerreadonlyPowerSyncLogger-CommonPowerSyncDatabase.logger
readyreadonlyboolean-CommonPowerSyncDatabase.ready
schemareadonlySchemaSchema used for the local database.CommonPowerSyncDatabase.schema
sdkVersionreadonlystring-CommonPowerSyncDatabase.sdkVersion
triggersreadonlyTriggerManagerExperimental Alpha Allows creating SQLite triggers which can be used to track various operations on SQLite tables.CommonPowerSyncDatabase.triggers

Accessors​

connected​
Get Signature​
get connected(): boolean;

Whether a connection to the PowerSync service is currently open.

Returns​

boolean

Inherited from​
CommonPowerSyncDatabase.connected
connecting​
Get Signature​
get connecting(): boolean;
Returns​

boolean

Inherited from​
CommonPowerSyncDatabase.connecting
database​
Get Signature​
get database(): DBAdapter;

The underlying database.

For the most part, behavior is the same whether querying on the underlying database, or on CommonPowerSyncDatabase.

Returns​

DBAdapter

Inherited from​
CommonPowerSyncDatabase.database

Methods​

close()​
close(options?): Promise<void>;

Close the database, releasing resources.

Also disconnects any active connection.

Once close is called, this connection cannot be used again - a new one must be constructed.

Parameters​
ParameterType
options?PowerSyncCloseOptions
Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.close
connect()​
connect(connector, options?): Promise<void>;

Connects to stream of events from the PowerSync instance.

Parameters​
ParameterType
connectorPowerSyncBackendConnector
options?SyncOptions
Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.connect
customQuery()​
customQuery<RowType>(query): Query<RowType>;

Allows building a WatchedQuery using an existing WatchCompatibleQuery. The watched query will use the provided WatchCompatibleQuery.execute method to query results.

Type Parameters​
Type Parameter
RowType
Parameters​
ParameterType
queryWatchCompatibleQuery<RowType[]>
Returns​

Query<RowType>

Example​

// Potentially a query from an ORM like Drizzle
const query = db.select().from(lists);

const watchedTodos = powersync.customQuery(query)
.watch()
// OR use .differentialWatch() for fine-grained watches.
Inherited from​
CommonPowerSyncDatabase.customQuery
disconnect()​
disconnect(): Promise<void>;

Close the sync connection.

Use CommonPowerSyncDatabase.connect to connect again.

Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.disconnect
disconnectAndClear()​
disconnectAndClear(options?): Promise<void>;

Disconnect and clear the database. Use this when logging out. The database can still be queried after this is called, but the tables would be empty.

To preserve data in local-only tables, set clearLocal to false.

Parameters​
ParameterType
options?DisconnectAndClearOptions
Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.disconnectAndClear
get()​
get<T>(sql, parameters?): Promise<T>;

Execute a read-only query and return the first result, error if the ResultSet is empty.

Type Parameters​
Type Parameter
T
Parameters​
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
Returns​

Promise<T>

The first result matching the query

Throws​

Error if no rows are returned

Inherited from​
CommonPowerSyncDatabase.get
getAll()​
getAll<T>(sql, parameters?): Promise<T[]>;

Execute a read-only query and return results.

Type Parameters​
Type Parameter
T
Parameters​
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
Returns​

Promise<T[]>

An array of results

Inherited from​
CommonPowerSyncDatabase.getAll
getClientId()​
getClientId(): Promise<string>;

Get an unique client id for this database.

The id is not reset when the database is cleared, only when the database is deleted.

Returns​

Promise<string>

A unique identifier for the database instance

Inherited from​
CommonPowerSyncDatabase.getClientId
getCrudBatch()​
getCrudBatch(limit?): Promise<CrudBatch>;

Get a batch of CRUD data to upload.

Returns null if there is no data to upload.

Use this from the PowerSyncBackendConnector.uploadData callback.

Once the data have been successfully uploaded, call CrudBatch.complete before requesting the next batch.

Use the limit parameter to specify the maximum number of updates to return in a single batch.

This method does include transaction ids in the result, but does not group data by transaction. One batch may contain data from multiple transactions, and a single transaction may be split over multiple batches.

Parameters​
ParameterTypeDescription
limit?numberMaximum number of CRUD entries to include in the batch
Returns​

Promise<CrudBatch>

A batch of CRUD operations to upload, or null if there are none

Inherited from​
CommonPowerSyncDatabase.getCrudBatch
getCrudTransactions()​
getCrudTransactions(): AsyncIterable<CrudTransaction, null>;

Returns an async iterator of completed transactions with local writes against the database.

This is typically used from the PowerSyncBackendConnector.uploadData callback. Each entry emitted by the returned iterator is a full transaction containing all local writes made while that transaction was active.

Unlike CommonPowerSyncDatabase.getNextCrudTransaction, which always returns the oldest transaction that hasn't been CrudTransaction.completed yet, this iterator can be used to receive multiple transactions. Calling CrudTransaction.complete will mark that and all prior transactions emitted by the iterator as completed.

This can be used to upload multiple transactions in a single batch, e.g with:

let lastTransaction = null;
let batch = [];

for await (const transaction of database.getCrudTransactions()) {
batch.push(...transaction.crud);
lastTransaction = transaction;

if (batch.length > 10) {
break;
}
}

If there is no local data to upload, the async iterator complete without emitting any items.

Note that iterating over async iterables requires a polyfill for React Native.

Returns​

AsyncIterable<CrudTransaction, null>

Inherited from​
CommonPowerSyncDatabase.getCrudTransactions
getNextCrudTransaction()​
getNextCrudTransaction(): Promise<CrudTransaction>;

Get the next recorded transaction to upload.

Returns null if there is no data to upload.

Use this from the PowerSyncBackendConnector.uploadData callback.

Once the data have been successfully uploaded, call CrudTransaction.complete before requesting the next transaction.

Unlike CommonPowerSyncDatabase.getCrudBatch, this only returns data from a single transaction at a time. All data for the transaction is loaded into memory.

Returns​

Promise<CrudTransaction>

A transaction of CRUD operations to upload, or null if there are none

Inherited from​
CommonPowerSyncDatabase.getNextCrudTransaction
getOptional()​
getOptional<T>(sql, parameters?): Promise<T>;

Execute a read-only query and return the first result, or null if the ResultSet is empty.

Type Parameters​
Type Parameter
T
Parameters​
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
Returns​

Promise<T>

The first result if found, or null if no results are returned

Inherited from​
CommonPowerSyncDatabase.getOptional
getUploadQueueStats()​
getUploadQueueStats(includeSize?): Promise<UploadQueueStats>;

Get upload queue size estimate and count.

Parameters​
ParameterType
includeSize?boolean
Returns​

Promise<UploadQueueStats>

Inherited from​
CommonPowerSyncDatabase.getUploadQueueStats
init()​
init(): Promise<void>;

Wait for initialization to complete. While initializing is automatic, this helps to catch and report initialization errors.

Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.init
onChange()​
Call Signature​
onChange(options?): AsyncIterable<WatchOnChangeEvent>;

This version of onChange uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.onChangeWithAsyncGenerator. Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.onChangeWithCallback.

Parameters​
ParameterType
options?SQLOnChangeOptions
Returns​

AsyncIterable<WatchOnChangeEvent>

Example​
async monitorChanges() {
for await (const event of this.powersync.onChange({tables: ['todos']})) {
console.log('Detected change event:', event);
}
}
Inherited from​
CommonPowerSyncDatabase.onChange
Call Signature​
onChange(handler?, options?): () => void;

See CommonPowerSyncDatabase.onChangeWithCallback.

Parameters​
ParameterType
handler?WatchOnChangeHandler
options?SQLOnChangeOptions
Returns​

() => void

Example​
monitorChanges() {
this.powersync.onChange({
onChange: (event) => {
console.log('Change detected:', event);
}
}, { tables: ['todos'] });
}
Inherited from​
CommonPowerSyncDatabase.onChange
onChangeWithAsyncGenerator()​
onChangeWithAsyncGenerator(options?): AsyncIterable<WatchOnChangeEvent>;

Create a Stream of changes to any of the specified tables.

This is preferred over CommonPowerSyncDatabase.watchWithAsyncGenerator when multiple queries need to be performed together when data is changed.

Note: do not declare this as async *onChange as it will not work in React Native.

Parameters​
ParameterTypeDescription
options?SQLWatchOptionsOptions for configuring watch behavior
Returns​

AsyncIterable<WatchOnChangeEvent>

An AsyncIterable that yields change events whenever the specified tables change

Inherited from​
CommonPowerSyncDatabase.onChangeWithAsyncGenerator
onChangeWithCallback()​
onChangeWithCallback(handler?, options?): () => void;

Invoke the provided callback on any changes to any of the specified tables.

This is preferred over CommonPowerSyncDatabase.watchWithCallback when multiple queries need to be performed together when data is changed.

Note that the onChange callback member of the handler is required.

Parameters​
ParameterTypeDescription
handler?WatchOnChangeHandlerCallbacks for handling change events and errors
options?SQLOnChangeOptionsOptions for configuring watch behavior
Returns​

A dispose function to stop watching for changes

() => void

Inherited from​
CommonPowerSyncDatabase.onChangeWithCallback
query()​
query<RowType>(query): Query<RowType>;

Allows defining a query which can be used to build a WatchedQuery. The defined query will be executed with CommonPowerSyncDatabase#getAll. An optional mapper function can be provided to transform the results.

Type Parameters​
Type Parameter
RowType
Parameters​
ParameterType
queryArrayQueryDefinition<RowType>
Returns​

Query<RowType>

Example​
const watchedTodos = powersync.query({
sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
parameters: [],
mapper: (row) => ({
...row,
created_at: new Date(row.created_at as string)
})
})
.watch()
// OR use .differentialWatch() for fine-grained watches.
Inherited from​
CommonPowerSyncDatabase.query
readLock()​
readLock<T>(callback): Promise<T>;

Takes a read lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.readTransaction should be used instead.

Type Parameters​
Type Parameter
T
Parameters​
ParameterType
callback(db) => Promise<T>
Returns​

Promise<T>

Inherited from​
CommonPowerSyncDatabase.readLock
readTransaction()​
readTransaction<T>(callback, lockTimeout?): Promise<T>;

Open a read-only transaction. When multiple connections are available, read transactions can run concurrently to a write transaction. Changes from any write transaction are not visible to read transactions started before it.

Type Parameters​
Type Parameter
T
Parameters​
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime in milliseconds to wait for a lock before throwing an error
Returns​

Promise<T>

The result of the callback

Throws​

Error if the lock cannot be obtained within the timeout period

Inherited from​
CommonPowerSyncDatabase.readTransaction
registerListener()​
registerListener(listener): () => void;
Parameters​
ParameterType
listenerPartial<T>
Returns​

() => void

Inherited from​
CommonPowerSyncDatabase.registerListener
requestCheckpoint()​
requestCheckpoint(): Promise<CheckpointRequest>;

Alpha

Requests a checkpoint from the PowerSync service.

The returned request can be awaited (using CheckpointRequest#waitForSync) to confirm that the local database has applied server-side changes up to the checkpoint. This method requires an active or connecting sync client connected with a CheckpointMode set to requests and PowerSync service version 1.24.0 or later.

It can throw for connection, mode, authentication, or service request failures.

Returns​

Promise<CheckpointRequest>

Inherited from​
CommonPowerSyncDatabase.requestCheckpoint
resolveTables()​
resolveTables(
sql,
parameters?,
options?): Promise<string[]>;

Resolves the list of tables that are used in a SQL query. If tables are specified in the options, those are used directly. Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.

Parameters​
ParameterTypeDescription
sqlstringThe SQL query to analyze
parameters?any[]Optional parameters for the SQL query
options?SQLWatchOptionsOptional watch options that may contain explicit table list
Returns​

Promise<string[]>

Array of table names that the query depends on

Inherited from​
CommonPowerSyncDatabase.resolveTables
syncStream()​
syncStream(name, params?): SyncStream;

Create a sync stream to query its status or to subscribe to it.

Parameters​
ParameterTypeDescription
namestringThe name of the stream to subscribe to.
params?Record<string, any>Optional parameters for the stream subscription.
Returns​

SyncStream

A SyncStream instance that can be subscribed to.

Inherited from​
CommonPowerSyncDatabase.syncStream
updateSchema()​
updateSchema(schema): Promise<void>;

Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.

Cannot be used while connected - this should only be called before CommonPowerSyncDatabase.connect.

Parameters​
ParameterType
schemaSchema
Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.updateSchema
waitForFirstSync()​
waitForFirstSync(request?): Promise<void>;

Wait for the first sync operation to complete.

Parameters​
ParameterTypeDescription
request?| AbortSignal | { priority?: number; signal?: AbortSignal; }Either an abort signal (after which the promise will complete regardless of whether a full sync was completed) or an object providing an abort signal and a priority target. When a priority target is set, the promise may complete when all buckets with the given (or higher) priorities have been synchronized. This can be earlier than a complete sync.
Returns​

Promise<void>

A promise which will resolve once the first full sync has completed.

Inherited from​
CommonPowerSyncDatabase.waitForFirstSync
waitForReady()​
waitForReady(): Promise<void>;
Returns​

Promise<void>

A promise which will resolve once initialization is completed.

Inherited from​
CommonPowerSyncDatabase.waitForReady
waitForStatus()​
waitForStatus(predicate, signal?): Promise<void>;

Waits for the first sync status for which the status callback returns a truthy value.

Parameters​
ParameterType
predicate(status) => any
signal?AbortSignal
Returns​

Promise<void>

Inherited from​
CommonPowerSyncDatabase.waitForStatus
watch()​
Call Signature​
watch(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>;

This version of watch uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.watchWithAsyncGenerator. Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.watchWithCallback.

Parameters​
ParameterType
sqlstring
parameters?any[]
options?SQLWatchOptions
Returns​

AsyncIterable<QueryResult<SqliteRecord>>

Example​
async *attachmentIds() {
for await (const result of this.powersync.watch(
`SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
[]
)) {
yield result.rows?._array.map((r) => r.id) ?? [];
}
}
Inherited from​
CommonPowerSyncDatabase.watch
Call Signature​
watch(
sql,
parameters?,
handler?,
options?): void;

See CommonPowerSyncDatabase.watchWithCallback.

Parameters​
ParameterType
sqlstring
parameters?any[]
handler?WatchHandler
options?SQLWatchOptions
Returns​

void

Example​
onAttachmentIdsChange(onResult) {
this.powersync.watch(
`SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
[],
{
onResult: (result) => onResult(result.rows?._array.map((r) => r.id) ?? [])
}
);
}
Inherited from​
CommonPowerSyncDatabase.watch
watchWithAsyncGenerator()​
watchWithAsyncGenerator(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>;

Execute a read query every time the source tables are modified. Use SQLOnChangeOptions.throttleMs to specify the minimum interval between queries. Source tables are automatically detected using EXPLAIN QUERY PLAN.

Parameters​
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
options?SQLWatchOptionsOptions for configuring watch behavior
Returns​

AsyncIterable<QueryResult<SqliteRecord>>

An AsyncIterable that yields QueryResults whenever the data changes

Inherited from​
CommonPowerSyncDatabase.watchWithAsyncGenerator
watchWithCallback()​
watchWithCallback(
sql,
parameters?,
handler?,
options?): void;

Execute a read query every time the source tables are modified. Use SQLOnChangeOptions.throttleMs to specify the minimum interval between queries. Source tables are automatically detected using EXPLAIN QUERY PLAN.

Note that the onChange callback member of the handler is required.

Parameters​
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
handler?WatchHandlerCallbacks for handling results and errors
options?SQLWatchOptionsOptions for configuring watch behavior
Returns​

void

Inherited from​
CommonPowerSyncDatabase.watchWithCallback
writeLock()​
writeLock<T>(callback): Promise<T>;

Takes a global lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.writeTransaction should be used instead.

Type Parameters​
Type Parameter
T
Parameters​
ParameterType
callback(db) => Promise<T>
Returns​

Promise<T>

Inherited from​
CommonPowerSyncDatabase.writeLock
writeTransaction()​
writeTransaction<T>(callback, lockTimeout?): Promise<T>;

Open a read-write transaction. This takes a global lock - only one write transaction can execute against the database at a time. Statements within the transaction must be done on the provided Transaction interface.

Type Parameters​
Type Parameter
T
Parameters​
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime in milliseconds to wait for a lock before throwing an error
Returns​

Promise<T>

The result of the callback

Throws​

Error if the lock cannot be obtained within the timeout period

Inherited from​
CommonPowerSyncDatabase.writeTransaction

PowerSyncNuxtModuleOptions​

Configuration options for the PowerSync Nuxt module.

Example​

export default defineNuxtConfig({
modules: ['@powersync/nuxt'],
powersync: {
useDiagnostics: true,
},
})

Properties​

PropertyTypeDescription
kysely?booleanEnable Kysely integration. When set to true, enables the usePowerSyncKysely composable for type-safe database queries. Requires @powersync/kysely-driver to be installed. Default false
useDiagnostics?booleanEnable diagnostics and the PowerSync Inspector. When set to true, enables diagnostics recording and makes the PowerSync Inspector available. The inspector provides real-time monitoring, data inspection, and debugging tools. Default false

UsePowerSyncInspectorDiagnosticsReturn​

Return type of usePowerSyncInspectorDiagnostics. Uses named types so the signature stays readable in docs and IDE.

Properties​

PropertyTypeDescription
bucketRowsReadonlyRef<BucketRow[] | null>-
clearData() => Promise<void>-
connectionOptionsComputedRef<SyncOptions>-
connectorComputedRef<PowerSyncBackendConnector>-
dbRef<CommonPowerSyncDatabase>-
downloadErrorReadonlyRef<unknown>-
downloadProgressDetailsReadonlyRef<unknown>-
formatBytes(bytes, decimals?) => string-
hasSyncedReadonlyRef<boolean>-
isConnectedReadonlyRef<boolean>-
isDiagnosticSchemaSetupReadonlyRef<boolean>-
isDownloadingReadonlyRef<boolean>-
isSyncingReadonlyRef<boolean>-
isUploadingReadonlyRef<boolean>-
lastSyncedAtReadonlyRef<Date | null>-
syncStatusReadonlyRef<SyncStatus>Current sync status. Typed as SyncStatus for a concise doc signature; at runtime it may be a readonly proxy.
tableRowsReadonlyRef<TableRow[] | null>-
totalDownloadProgressReadonlyRef<string>-
totalsReadonlyRef<UsePowerSyncInspectorDiagnosticsTotals>-
uploadErrorReadonlyRef<unknown>-
uploadQueueCountReadonlyRef<number>-
uploadQueueSizeReadonlyRef<string>-
uploadQueueStatsReadonlyRef<UploadQueueStats | null>-
userIDReadonlyRef<string | null>-

Type Aliases​

UsePowerSyncInspectorDiagnosticsTotals​

type UsePowerSyncInspectorDiagnosticsTotals = {
buckets: number;
data_size: string;
download_size: string;
downloaded_operations: number | undefined;
metadata_size: string;
row_count: number;
total_operations: number;
};

Aggregated statistics from the diagnostics composable.

Properties​

PropertyType
bucketsnumber
data_sizestring
download_sizestring
downloaded_operationsnumber | undefined
metadata_sizestring
row_countnumber
total_operationsnumber

Variables​

NuxtPowerSyncDatabase​

const NuxtPowerSyncDatabase: PowerSyncDatabaseConstructor<WebPowerSyncDatabaseOptions> = NuxtDatabaseImplementation;

An extended PowerSync database class that includes diagnostic capabilities for use with the PowerSync Inspector.

This class automatically configures diagnostics when useDiagnostics: true is set in the module configuration. It provides enhanced VFS support, schema management, and logging capabilities for the inspector.

Example​

import { NuxtPowerSyncDatabase } from '@powersync/nuxt'

const db = new NuxtPowerSyncDatabase({
database: {
dbFilename: 'your-db-filename.sqlite',
},
schema: yourSchema,
})

Remarks​

  • When diagnostics are enabled, automatically uses cooperative sync VFS for improved compatibility
  • Stores connector internally for inspector access
  • Integrates with dynamic schema management for inspector features
  • Automatically configures logging when diagnostics are enabled
  • When diagnostics are disabled, behaves like a standard PowerSyncDatabase

Functions​

FunctionDescription
useDiagnosticsLoggerProvides a logger configured for PowerSync diagnostics.
usePowerSyncInspectorA composable for setting up PowerSync Inspector functionality.
usePowerSyncInspectorDiagnosticsA comprehensive composable that provides real-time diagnostics data and sync status monitoring for your PowerSync client and local database.
usePowerSyncKyselyProvides a Kysely-wrapped PowerSync database for type-safe database queries.