Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Projects and Practice

Project: A Markdown Notes App with Tauri

Plan and build a safe Markdown notes app with Tauri 2: project layout, Rust commands, file storage, capabilities, preview rendering with escaping, search and tests, with a runnable core model.

Time to put the chapters together. In this project you design a small but real desktop app: Notes, which stores Markdown notes as files, lists and searches them, shows a live preview and saves automatically. It uses commands, plugins, capabilities, validation, testing and packaging, so it is a good rehearsal for any Tauri app you build next.

You do not need to type everything at once. Read the plan, run the core model here in the page, then build the real thing locally step by step. The pieces link back to Files and Dialogs, Scopes and Input Validation and Testing Tauri Apps.

Real versus stand-in. The bash, rust, json and ts blocks are real Tauri 2 code. Tauri cannot run on this site, so the runnable blocks implement the app's core logic (note storage, Markdown rendering, search) in plain JavaScript. Port the same design to Rust for the real app.

Requirements

  1. Notes live as .md files in the app data folder, one file per note.
  2. The sidebar lists notes, newest first, with a search box.
  3. The editor has a live preview. Markdown is rendered safely (no raw HTML from notes).
  4. Changes are saved automatically a moment after typing stops.
  5. A user can export a note with a native Save dialog.
  6. The app asks for the smallest possible permissions.

Architecture

flowchart LR
  UI["Frontend<br/>list, editor, preview"] -->|invoke| Cmd["Rust commands<br/>list_notes, read_note,<br/>save_note, delete_note"]
  Cmd --> Core["notes.rs<br/>validation, file names"]
  Core --> Disk[("AppData/notes/*.md")]
  UI -->|plugin| Dlg["dialog + fs<br/>export only"]

The frontend never builds paths. It sends a note id and Rust decides where the file lives.

Create the project and add plugins:

Terminal
npm create tauri-app@latest notes
cd notes
npm run tauri add dialog
npm run tauri add fs

Rust: the commands

Design rule: the frontend uses ids, never file paths. An id is a lowercase slug such as meeting-notes, validated strictly.

Rust
// src-tauri/src/notes.rs
use std::{fs, path::PathBuf};
use serde::Serialize;
use tauri::{AppHandle, Manager};

#[derive(Serialize)]
pub struct NoteInfo {
    pub id: String,
    pub title: String,
    pub modified_ms: u64,
}

fn notes_dir(app: &AppHandle) -> Result<PathBuf, String> {
    let dir = app.path().app_data_dir().map_err(|e| e.to_string())?.join("notes");
    fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    Ok(dir)
}

pub fn valid_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 80
        && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        && !id.starts_with('-')
}

fn note_path(app: &AppHandle, id: &str) -> Result<PathBuf, String> {
    if !valid_id(id) {
        return Err("invalid note id".into());
    }
    Ok(notes_dir(app)?.join(format!("{id}.md")))
}

#[tauri::command]
pub fn list_notes(app: AppHandle) -> Result<Vec<NoteInfo>, String> {
    let mut notes = Vec::new();
    for entry in fs::read_dir(notes_dir(&app)?).map_err(|e| e.to_string())?.flatten() {
        let path = entry.path();
        let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(String::from) else { continue };
        if path.extension().and_then(|e| e.to_str()) != Some("md") || !valid_id(&id) { continue }
        let text = fs::read_to_string(&path).unwrap_or_default();
        let title = text.lines().next().unwrap_or("").trim_start_matches('#').trim().to_string();
        let modified_ms = entry.metadata().and_then(|m| m.modified()).ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_millis() as u64).unwrap_or(0);
        notes.push(NoteInfo { id, title: if title.is_empty() { "Untitled".into() } else { title }, modified_ms });
    }
    notes.sort_by(|a, b| b.modified_ms.cmp(&a.modified_ms));
    Ok(notes)
}

#[tauri::command]
pub fn read_note(app: AppHandle, id: String) -> Result<String, String> {
    fs::read_to_string(note_path(&app, &id)?).map_err(|e| e.to_string())
}

#[tauri::command]
pub fn save_note(app: AppHandle, id: String, body: String) -> Result<(), String> {
    if body.len() > 2_000_000 {
        return Err("note is too large".into());
    }
    fs::write(note_path(&app, &id)?, body).map_err(|e| e.to_string())
}

#[tauri::command]
pub fn delete_note(app: AppHandle, id: String) -> Result<(), String> {
    fs::remove_file(note_path(&app, &id)?).map_err(|e| e.to_string())
}

Register them in lib.rs with generate_handler![list_notes, read_note, save_note, delete_note]. Put them under the access-control system by listing them in build.rs (see Capabilities and Permissions) and grant them to the main window only. The capability then needs no fs permission at all, because the frontend never touches files directly. For export, add dialog:allow-save and fs:allow-write-text-file; the user's chosen path is added to the scope for that session.

The core model you can run

The next block is the heart of the app in JavaScript: id rules, a store with title extraction, a safe Markdown renderer (headings, bold, italic, code, lists and links with http/https only) and search. Run it, change the notes, break the rules.

Node.js Core model: store, safe Markdown and search

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.

Look at the XSS note. The <script> and <img onerror> become visible text, and the javascript: link is left as plain text because only http and https are turned into links. If you use a Markdown library in the real app (such as marked or markdown-it), still run its output through a sanitizer like DOMPurify, and keep the CSP strict (CSP and Isolation).

Auto-save with debounce

On every keystroke call save_note? That would write the file hundreds of times. Wait until typing pauses, and save on blur or close too.

TypeScript
import { invoke } from '@tauri-apps/api/core';

let timer: number | undefined;

export function scheduleSave(id: string, body: string, onState: (s: 'saving' | 'saved' | 'error') => void) {
  clearTimeout(timer);
  onState('saving');
  timer = window.setTimeout(async () => {
    try {
      await invoke('save_note', { id, body });
      onState('saved');
    } catch {
      onState('error');
    }
  }, 600);
}
Node.js Core model: debounced save with state

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.

Testing, packaging and next steps

  1. Unit test valid_id and the title logic with cargo test; test the editor component with mockIPC (testing).
  2. Add an E2E test of "create, type, see it in the list" (E2E).
  3. Build installers and sign them (bundling), and add the updater.

Stretch goals: tags, a trash folder instead of deleting, window-state so the app remembers its size, full-text search in SQLite (store and SQL), and drag and drop of .md files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the frontend send note ids instead of file paths?

    With ids only, path traversal becomes impossible by design, and the frontend needs no fs permission.
  2. 2. In the safe renderer, why is the text escaped before our own tags are added?

    Escaping first guarantees that only the tags we add are real HTML.
  3. 3. Why debounce auto-save?

    Waiting for a pause batches many changes into one write.
  4. 4. Which capabilities does the notes window need for the core features if commands handle all file access?

    Moving file access into validated Rust commands keeps the frontend's permissions tiny.

Summary

  • Design around ids and validated Rust commands; the frontend never builds paths.
  • Render Markdown safely: escape first, allow only http/https links, keep CSP strict.
  • Debounce saving and report saving, saved and error states.
  • Test the core logic, mock IPC in frontend tests, then package, sign and update.

Next: Project: A System Monitor