Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Plugins and Native Features

Store, SQL and App Settings in Tauri

Save settings with the Tauri store plugin, use SQLite through the sql plugin, pick the right storage for the data, and practice with runnable stand-ins of debounced saves and migrations.

Almost every app needs to remember something: the dark-mode choice, the last opened folder, a list of notes, a shopping history. In a browser you would reach for localStorage. In a Tauri app you have better tools, and the right one depends on how much data you have and how it is shaped.

This lesson covers the two official plugins for persistent data, store for small settings and sql for real databases, and gives you a way to choose between them. It builds on Files and Dialogs, because both plugins keep their data in files under your app's data folder.

Real versus stand-in. ts, rust, toml, sql and json blocks are real Tauri code to read. The runnable node blocks re-create the ideas (debounced saving, versioned migrations) in memory.

Choosing a storage

Need Use
A handful of settings (theme, window size, last file) store plugin
Many records, search, sorting, relations sql plugin (SQLite)
Documents the user opens and saves Plain files with the fs plugin
Secrets such as tokens The OS keychain (a keyring crate) or the Stronghold plugin, never plain JSON
Temporary data for the current session Variables in memory

localStorage still works in the webview, but it lives inside the webview's profile, is easier to lose, and is not reachable from Rust. For anything important, prefer the plugins.

The store plugin

The store is a persistent key-value map saved as a JSON file in the app data folder.

Terminal
npm run tauri add store
Rust
.plugin(tauri_plugin_store::Builder::new().build())
JSON
{ "permissions": ["core:default", "store:default"] }
TypeScript
import { load } from '@tauri-apps/plugin-store';

// Creates settings.json in the app data folder if it does not exist
const store = await load('settings.json', { autoSave: true });

await store.set('theme', 'dark');
await store.set('recentFiles', ['a.md', 'b.md']);

const theme = await store.get<string>('theme');   // 'dark'
const has = await store.has('theme');             // true
await store.delete('theme');
const keys = await store.keys();

await store.save(); // force a write; autoSave also writes soon after changes

Three details worth knowing:

  • Values can be anything JSON can hold (strings, numbers, booleans, arrays, objects).
  • get returns undefined for a missing key, so give your own default: (await store.get('theme')) ?? 'system'.
  • Saving is debounced: rapid changes are batched into one disk write, so slider movements do not hammer the disk.

Stores can also be created in Rust, so your commands and your frontend read the same file:

Rust
use tauri_plugin_store::StoreExt;

#[tauri::command]
fn theme(app: tauri::AppHandle) -> String {
    let store = app.store("settings.json").expect("store");
    store
        .get("theme")
        .and_then(|v| v.as_str().map(String::from))
        .unwrap_or_else(|| "system".into())
}

The stand-in below shows how a debounced autosave behaves, which explains why a crash a few milliseconds after a change can lose it, and why you call save() at important moments such as quitting.

Node.js Stand-in: a key-value store with debounced autosave

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Five fast changes produced one disk write, and the explicit save() wrote at once. The pending timer is cleared so you do not write twice.

The sql plugin

For lists of things, a database is easier than a JSON file: you can filter, sort and join without loading everything. The sql plugin wraps sqlx and supports SQLite, MySQL and PostgreSQL. For desktop apps, SQLite is almost always the right choice, because it is a single file with no server.

Terminal
npm run tauri add sql
TOML
# src-tauri/Cargo.toml
tauri-plugin-sql = { version = "2", features = ["sqlite"] }

Migrations are written in Rust and run when the app starts, so every user's database upgrades safely:

Rust
use tauri_plugin_sql::{Migration, MigrationKind};

let migrations = vec![
    Migration {
        version: 1,
        description: "create_notes",
        sql: "CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT);",
        kind: MigrationKind::Up,
    },
    Migration {
        version: 2,
        description: "add_pinned",
        sql: "ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;",
        kind: MigrationKind::Up,
    },
];

tauri::Builder::default().plugin(
    tauri_plugin_sql::Builder::default()
        .add_migrations("sqlite:notes.db", migrations)
        .build(),
)

From the frontend:

TypeScript
import Database from '@tauri-apps/plugin-sql';

const db = await Database.load('sqlite:notes.db');

await db.execute('INSERT INTO notes (title, body) VALUES ($1, $2)', ['Plan', 'Ship it']);

const rows = await db.select<{ id: number; title: string }[]>(
  'SELECT id, title FROM notes WHERE pinned = $1 ORDER BY id DESC',
  [1],
);

Always pass values as parameters ($1, $2) and never glue user text into the SQL string; otherwise you open the door to SQL injection. If you want to learn more SQL, the SQL tutorial covers it in depth.

Another approach is to keep the database entirely in Rust (with rusqlite or sqlx) and expose your own commands such as list_notes. Then the frontend never sends raw SQL, which is a tighter security story (see Security Model).

How migrations work

A database remembers its schema version. At startup you apply every migration whose version is higher than the stored one, in order, exactly once. The stand-in below models that.

Node.js Stand-in: versioned migrations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never edit an old migration after release. Add a new one instead, because some users already ran the old version.

Where the data lives

Both plugins put files under the app data directory, which depends on your bundle identifier from tauri.conf.json (for example com.example.notes). Typical locations are %APPDATA%\com.example.notes on Windows, ~/Library/Application Support/com.example.notes on macOS and ~/.local/share/com.example.notes on Linux. Uninstalling the app usually keeps this folder, so be thoughtful about what you store and offer an "export" or "delete my data" button.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which storage fits a theme choice and a last-opened-file path best?

    A few small settings are exactly what the key-value store is designed for.
  2. 2. Why is autosave in the store plugin debounced?

    Debouncing waits briefly after the last change, so many quick updates cause one write.
  3. 3. How should user text go into a SQL query from the frontend?

    Bound parameters keep data separate from SQL and prevent injection.
  4. 4. You shipped migration 2 and found a typo in it. What is the right fix?

    Users who already applied version 2 will never run it again, so corrections must be a new, higher version.
  5. 5. Which is the best place for an API token?

    Tokens are secrets. Plain JSON files are readable by anyone with access to the user folder.

Summary

  • Use store for small settings, sql (SQLite) for structured data, fs for user documents, and the OS keychain for secrets.
  • The store is a JSON key-value file with debounced autosave; call save() at important moments.
  • SQL migrations are versioned, run once and in order, and should never be edited after release.
  • Use bound parameters, or keep SQL in Rust behind your own commands.

Next: Notifications, Clipboard, Shortcuts and OS Info