See how Capacitor fits into the entire Ionic Ecosystem ->
Capacitor is part of the Ionic Ecosystem ->

Data Storage in Capacitor

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 Capacitor apps run primarily in a web view or browser, Web APIs for storage are available to Capacitor 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.

Capacitor Storage API

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

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

import { Plugins } from '@capacitor/core';

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

// JSON "get" example
async getObject() {
  const ret = await Storage.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, there are a few options.

The most widely supported option is SQLite. There are a number of community-maintained SQLite plugins that should work in Capacitor, including capacitor-sqlite and cordova-plugin-sqlite.

The Capacitor team also offers an enterprise SQLite storage solution with encryption support and integration with secure key management APIs on device.

Contributors

BackNext