Skip to main content

Data Storage in Napacitor

Most apps need to persist and read local data. Depending on the specific use case, there are a few approaches one can take.

Why can't I just use LocalStorage or IndexedDB?​

Since Napacitor apps run primarily in a web view or browser, Web APIs for storage are available to Napacitor developers. However, there are some major caveats to keep in mind with these APIs.

Local Storage can be used for small amounts of temporary data, such as a user id, but must be considered transient, meaning your app needs to expect that the data will be lost eventually. This is because the OS will reclaim local storage from Web Views if a device is running low on space. The same can be said for IndexedDB at least on iOS (on Android, the persisted storage API is available to mark IndexedDB as persisted). Read more on data storage eviction policies in the browser.

Napacitor Preferences API​

Napacitor comes with a native Preferences API that avoids the eviction issues above, but is meant for small amounts of data.

The Preferences API provides a simple key/value API with no advanced query support:

import { Preferences } from '@napacitor/preferences';

// JSON "set" example
async setObject() {
await Preferences.set({
key: 'user',
value: JSON.stringify({
id: 1,
name: 'Max'
})
});
}

// JSON "get" example
async getObject() {
const ret = await Preferences.get({ key: 'user' });
const user = JSON.parse(ret.value);
}

Large data or high performance storage options​

For storing large amounts of data and accessing it in a high performance way, the recommended option is SQLite.

Napacitor provides an official SQLite database plugin (@napacitor/database-sqlite), implemented in C# on top of Microsoft.Data.Sqlite — one codebase covering Android, iOS, Mac Catalyst, and Windows. It exposes execute / run / query methods with parameter binding and transaction support:

import { DatabaseSqlite } from '@napacitor/database-sqlite';

// Create a table
await DatabaseSqlite.execute({
statements:
'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);',
});

// Insert (with parameter binding to prevent SQL injection)
await DatabaseSqlite.run({
statement: 'INSERT INTO users (name) VALUES (?);',
values: ['Max'],
});

// Query: each row comes back as a column name → value object
const result = await DatabaseSqlite.query({
statement: 'SELECT * FROM users WHERE name = ?;',
values: ['Max'],
});
console.log(result.values); // [{ id: 1, name: 'Max' }]

If you prefer not to use the official plugin, you can also use Microsoft.Data.Sqlite or SQLite-net on the C# side and wrap it as a custom Napacitor plugin to expose it to your web code.