Tauri Commands Tutorial: Frontend to Backend Communication with Rust & JavaScript
Video: Tauri Commands Tutorial: Frontend to Backend Communication with Rust & JavaScript by Taught by Celeste AI - AI Coding Coach
Watch full page →Tauri Commands Tutorial: Frontend to Backend Communication with Rust & JavaScript
This tutorial demonstrates how to create and use Tauri commands to enable seamless communication between a JavaScript frontend and a Rust backend. You will learn how to define commands in Rust using the #[tauri::command] attribute, invoke them from JavaScript, pass multiple parameters, handle results, and manage errors effectively.
Code
use tauri::command;
// Default greet command exposed to the frontend
#[command]
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
// Calculator command with multiple parameters and error handling
#[command]
fn calculate(a: i32, b: i32, operation: &str) -> Result {
match operation {
"add" => Ok(a + b),
"subtract" => Ok(a - b),
"multiply" => Ok(a * b),
"divide" => {
if b == 0 {
Err("Cannot divide by zero".into())
} else {
Ok(a / b)
}
}
_ => Err(format!("Unsupported operation: {}", operation)),
}
}
// In main.rs or lib.rs, register the commands
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet, calculate])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
/* JavaScript frontend example (e.g., main.ts) */
import { invoke } from '@tauri-apps/api/tauri';
// Calling the greet command
async function greetUser(name) {
const message = await invoke('greet', { name });
console.log(message); // "Hello, {name}!"
}
// Calling the calculate command
async function calculateResult(a, b, operation) {
try {
const result = await invoke('calculate', { a, b, operation });
console.log(`Result: ${result}`);
} catch (error) {
console.error('Calculation error:', error);
}
}
Key Points
- The
#[tauri::command]attribute exposes Rust functions as commands callable from JavaScript. - Commands must be registered with
invoke_handlerusinggenerate_handler!to be accessible. - The JavaScript
invoke()function calls Rust commands by name and passes arguments as an object. - Rust commands can return
Resulttypes to handle success and error cases cleanly. - JavaScript receives command results as promises, allowing easy async handling and error catching.