Tauri tutorial: build a desktop app with web technologies

By

Updated

Tagged: JavaScript

Build a Tauri 2 desktop notes app with HTML, CSS, TypeScript, a Rust command, local file storage, permissions, development, and packaging.

Tauri lets you build desktop apps using a web frontend and a Rust backend.

You write the interface in HTML, CSS, and TypeScript, and Tauri renders it inside the operating system’s own webview instead of bundling a whole browser engine with every app. On the native side, Rust handles the heavy lifting and exposes only the specific commands you want the frontend to call.

In this tutorial we’ll build a small notes app with Tauri 2. It will:

Install the prerequisites

Before we start, you’ll need a few things installed on your machine:

Follow the platform setup steps in the Tauri docs before going further. On macOS, that means installing the Xcode command-line tools. Windows uses WebView2, and on Linux the system packages depend on your distro.

Once Rust is installed, check that it’s available in your terminal:

rustc --version
cargo --version

Create the project

Let’s scaffold a new Tauri project from the terminal:

npm create tauri-app@latest

When the prompts come up, name the project tauri-notes and pick these options:

Next, move into the project folder and start it up:

cd tauri-notes
npm install
npm run tauri dev

The first run takes a bit of time because Cargo has to compile all the Rust dependencies from scratch. After that, rebuilds are incremental and much faster. Once it finishes, Tauri opens a real desktop window running your Vite frontend.

Understand the project

Here are the main directories you’ll work with:

src/                  web frontend
src-tauri/
  src/                Rust code
  capabilities/       frontend permissions
  Cargo.toml          Rust dependencies
  tauri.conf.json     application configuration

One thing to keep in mind from the start: your frontend doesn’t get unlimited access to the computer. It can only call the Tauri APIs and Rust commands you allow in your Rust code and capability files.

Build the notes interface

Let’s set up a clean UI for editing a note. Replace the main frontend HTML with this:

<main>
  <h1>Notes</h1>
  <label for="note">Your note</label>
  <textarea id="note" rows="14"></textarea>
  <div>
    <span id="status" aria-live="polite"></span>
    <button id="save" type="button">Save</button>
  </div>
</main>

<script type="module" src="/src/main.ts"></script>

Then add some light CSS to style it:

:root {
  font-family: system-ui, sans-serif;
  color-scheme: light dark;
}

body {
  margin: 0;
}

main {
  max-width: 720px;
  margin: 0 auto;
  padding: 32px;
}

textarea {
  box-sizing: border-box;
  width: 100%;
  padding: 12px;
  font: inherit;
}

main div {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}

Add the filesystem plugin

Tauri keeps most native features out of the core and ships them as plugins instead. From your project root, add the filesystem plugin:

npm run tauri add fs

That installs the Rust crate, adds the JavaScript package, and sets up the plugin in your app.

Now open src/main.ts and hook it up:

import {
  BaseDirectory,
  exists,
  mkdir,
  readTextFile,
  writeTextFile,
} from '@tauri-apps/plugin-fs'

function requiredElement<T extends Element>(selector: string): T {
  const element = document.querySelector<T>(selector)

  if (!element) {
    throw new Error(`Missing required element: ${selector}`)
  }

  return element
}

const noteElement = requiredElement<HTMLTextAreaElement>('#note')
const saveButton = requiredElement<HTMLButtonElement>('#save')
const statusElement = requiredElement<HTMLElement>('#status')

const notesDirectory = 'notes'
const notePath = `${notesDirectory}/note.txt`

async function ensureNotesDirectory(): Promise<void> {
  await mkdir(notesDirectory, {
    baseDir: BaseDirectory.AppData,
    recursive: true,
  })
}

async function loadNote(): Promise<void> {
  await ensureNotesDirectory()

  const found = await exists(notePath, {
    baseDir: BaseDirectory.AppData,
  })

  if (found) {
    noteElement.value = await readTextFile(notePath, {
      baseDir: BaseDirectory.AppData,
    })
  }
}

async function saveNote(): Promise<void> {
  await ensureNotesDirectory()

  await writeTextFile(notePath, noteElement.value, {
    baseDir: BaseDirectory.AppData,
  })

  statusElement.textContent = 'Saved'

  setTimeout(() => {
    statusElement.textContent = ''
  }, 1200)
}

saveButton.addEventListener('click', () => {
  void saveNote().catch((error: unknown) => {
    statusElement.textContent = String(error)
  })
})

void loadNote().catch((error: unknown) => {
  statusElement.textContent = `Could not load note: ${String(error)}`
})

Notice we’re using BaseDirectory.AppData instead of stitching together a home directory path by hand. Tauri resolves it to the right app-specific data folder on every operating system.

Grant the smallest filesystem permission

Installing a plugin doesn’t mean every frontend window can call every command in it. You have to grant those permissions explicitly in src-tauri/capabilities/default.json.

The generated plugin setup can add broader filesystem access than you want. For this app, restrict it to just the commands and scope needed for the app data directory:

{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "description": "Permissions for the main window",
  "windows": ["main"],
  "permissions": [
    "core:default",
    "fs:deny-default",
    "fs:create-app-specific-dirs",
    {
      "identifier": "fs:allow-mkdir",
      "allow": [
        { "path": "$APPDATA/notes" }
      ]
    },
    {
      "identifier": "fs:allow-exists",
      "allow": [
        { "path": "$APPDATA/notes/note.txt" }
      ]
    },
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [
        { "path": "$APPDATA/notes/note.txt" }
      ]
    },
    {
      "identifier": "fs:allow-write-text-file",
      "allow": [
        { "path": "$APPDATA/notes/note.txt" }
      ]
    }
  ]
}

Permission names can change across plugin releases. If you want to see which permissions your installed version exposes, run:

npm run tauri permission ls

Think of a capability file as answering two questions:

If your app only needs one private file, don’t hand it the entire home directory.

Call Rust from JavaScript

The filesystem plugin is already enough to save and load notes, though custom Rust commands are how you build your own native logic.

Open src-tauri/src/lib.rs and add a command:

#[tauri::command]
fn note_summary(note: String) -> String {
    let words = note.split_whitespace().count();
    format!("{} words", words)
}

Next, register that command in the builder so the frontend can reach it:

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_fs::init())
        .invoke_handler(tauri::generate_handler![note_summary])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Over in your frontend code, import invoke:

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

Then call it to update the status while you type:

noteElement.addEventListener('input', () => {
  void invoke<string>('note_summary', {
    note: noteElement.value,
  })
    .then((summary) => {
      statusElement.textContent = summary
    })
    .catch((error: unknown) => {
      statusElement.textContent = String(error)
    })
})

Tauri serializes the JavaScript arguments and passes them to your Rust function, with command argument keys using camelCase by default. On the JavaScript side, the command returns a promise.

Return errors instead of panicking

Any command that can fail should return a Result instead of crashing. Here’s how that looks in Rust:

#[tauri::command]
fn validate_note(note: String) -> Result<(), String> {
    if note.len() > 100_000 {
        return Err("The note is too large".into());
    }

    Ok(())
}

Then handle the error in JavaScript:

async function saveNote(): Promise<void> {
  await invoke<void>('validate_note', {
    note: noteElement.value,
  })

  await ensureNotesDirectory()

  await writeTextFile(notePath, noteElement.value, {
    baseDir: BaseDirectory.AppData,
  })

  statusElement.textContent = 'Saved'
}

Make sure you register both commands in your existing builder:

.invoke_handler(tauri::generate_handler![
    note_summary,
    validate_note
])

Don’t use unwrap() on user input or expected runtime failures, because a Rust panic makes for a terrible validation message.

Keep in mind that this Rust check only gives you a shared validation rule. Because the permitted frontend can still call writeTextFile() directly, it isn’t a real security boundary. If you need a size limit that can’t be bypassed, move both saving and validation into one Rust command and remove direct frontend write permission.

Develop without exposing a web server

During development, Tauri starts the Vite dev server and points the desktop webview at it. In a production build, your frontend assets are bundled right inside the app, so the person running it doesn’t need Node.js or a local server.

Be deliberate about frontend network access, because a desktop app can still run into web security problems:

Use a restrictive content security policy, keep your dependencies up to date, and grant narrow capabilities.

Build the desktop application

When you’re ready to package the app, run:

npm run tauri build

Tauri builds the app and puts the platform-specific installer or bundle in src-tauri/target/release/bundle.

Getting a local build is only the first step before handing it to users. For real distribution, you’ll also need:

On macOS, you’ll go through that notarization step whether you ship a zip or a DMG installer.

As a rule, build Windows installers on Windows and macOS bundles on macOS unless the platform docs explicitly support your cross-compilation setup.

What belongs in Rust?

Don’t move code to Rust just because Tauri includes it. Keep your presentation and everyday UI state in the frontend where it’s easy to work with.

Save Rust and official plugins for the native work:

Every command you expose widens what the frontend can ask the operating system to do, so keep that list small. If something can live in the frontend without extra permissions, leave it there.

Want me to talk about your product? You can sponsor this site.

Related posts about js: