Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Commands and Events

Tauri Commands: Calling Rust from JavaScript

Write your first Tauri commands: the #[tauri::command] attribute, generate_handler!, invoke() from JavaScript, return values, naming rules and organizing commands in modules.

Commands are the main bridge between your frontend and your Rust code. A command is a Rust function that JavaScript can call by name and get a result back from. Nearly every real Tauri app is built from a collection of them.

Commands need the real Tauri runtime, which cannot run on this page. The Rust below is read-only, and each live example is a JavaScript stand-in that reproduces the same behavior so you can experiment with it.

The three steps

  1. Write a Rust function and mark it with #[tauri::command].
  2. Register it with invoke_handler(tauri::generate_handler![...]).
  3. Call it from JavaScript with invoke.
Rust
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

pub fn run() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
TypeScript
import { invoke } from "@tauri-apps/api/core";

const message = await invoke<string>("greet", { name: "Ada" });
console.log(message); // Hello, Ada!

invoke takes the command name as a string and an optional object of arguments. It returns a Promise with the function's return value.

generate_handler! must be called once, with all commands in one list. Calling .invoke_handler a second time replaces the first. A command that exists but is not in the list fails with "command not found".

Argument names: camelCase in JavaScript

Rust uses snake_case, JavaScript uses camelCase. Tauri converts for you: a Rust parameter user_name is passed from JavaScript as userName.

Rust
#[tauri::command]
fn rename_note(note_id: u32, new_title: String) -> String {
    format!("note {note_id} is now '{new_title}'")
}
TypeScript
await invoke("rename_note", { noteId: 7, newTitle: "Groceries" });

If you prefer snake_case on both sides, add #[tauri::command(rename_all = "snake_case")] and pass { note_id: 7, new_title: "..." }.

The command name is the Rust function name as written: rename_note stays rename_note in invoke.

What can be an argument or return value?

Anything that serde can convert to or from JSON: numbers, booleans, strings, Vec<T>, Option<T>, HashMap<String, T>, tuples, and your own structs and enums that derive Serialize (return values) and Deserialize (arguments). Option<T> parameters become optional: undefined or a missing key gives None.

Rust
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct NewNote {
    title: String,
    tags: Vec<String>,
}

#[derive(Serialize)]
struct Note {
    id: u32,
    title: String,
    tags: Vec<String>,
}

#[tauri::command]
fn create_note(note: NewNote) -> Note {
    Note { id: 1, title: note.title, tags: note.tags }
}
TypeScript
interface Note { id: number; title: string; tags: string[] }
const note = await invoke<Note>("create_note", {
  note: { title: "Ideas", tags: ["work", "later"] },
});

Keep a TypeScript type that mirrors your Rust struct. Tools exist that generate bindings for you, but a hand-written interface is a fine start.

Commands with special parameters

Besides your own arguments, a command can request things Tauri provides. They are not passed from JavaScript:

  • State<'_, T>: managed state (see State management).
  • AppHandle: a handle to the whole app, to emit events, create windows or read paths.
  • WebviewWindow or Window: the window that made the call.
Rust
#[tauri::command]
fn who_called(window: tauri::WebviewWindow) -> String {
    format!("called from window '{}'", window.label())
}

Organizing commands

Put commands in modules and register them with their full path:

Rust
mod notes;   // src/notes.rs contains #[tauri::command] pub fn list_notes() ...

tauri::Builder::default()
    .invoke_handler(tauri::generate_handler![
        greet,
        notes::list_notes,
        notes::create_note
    ])

Commands in a module must be pub. A known restriction: a #[tauri::command] function in the crate root lib.rs cannot be pub; in other modules it must be.

Return values the frontend can rely on

Return plain data and keep each command focused. A good command is small: it validates input, calls your logic, and returns a result. Put the real logic in ordinary Rust functions that you can unit-test without Tauri, and let the command be a thin wrapper.

Try it: a command registry (stand-in)

This stand-in mirrors generate_handler! and invoke: commands are registered by name, arguments arrive as an object with camelCase keys that are mapped to snake_case parameters, and unknown commands reject.

Node.js Stand-in: invoke and generate_handler

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.

Try it: structs across the bridge (stand-in)

Here the "Rust" command receives a deserialized struct and returns a new one. The JSON round trip shows what actually crosses.

Node.js Stand-in: structs become JSON

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.

Common mistakes

  • Using snake_case in JavaScript arguments: { note_id: 7 } does not match noteId, so Tauri reports a missing argument.
  • Forgetting to add the command to generate_handler!.
  • Returning a type that does not derive Serialize: a compile error pointing at the command.
  • Making a command do slow blocking work; see Async commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does JavaScript pass a Rust parameter named user_name?

    By default Tauri maps camelCase keys from JavaScript to snake_case Rust parameters.
  2. 2. What must you do after writing a #[tauri::command] function?

    Only registered commands are reachable from the frontend.
  3. 3. What does invoke return?

    The call crosses the IPC bridge, so the result is asynchronous.
  4. 4. Which parameter type is injected by Tauri rather than passed from JavaScript?

    State, AppHandle and window types are provided by Tauri.

Summary

  • A command is a Rust function marked #[tauri::command], registered with generate_handler! and called with invoke.
  • JavaScript uses camelCase argument keys; Rust uses snake_case.
  • Arguments and results must be serde-compatible (JSON-like data).
  • Commands can request State, AppHandle and window parameters that Tauri injects.
  • Keep commands thin and put logic in plain functions.

Next: Command arguments, errors and Result