Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Plugins and Native Features

Writing a Custom Tauri Plugin

Build your own Tauri 2 plugin: scaffold it, add commands, managed state and events, generate permissions, wrap it in a typed JavaScript API, and try a runnable stand-in of the plugin builder.

Sooner or later you will write a piece of native logic that you want to reuse: a barcode decoder, a wrapper for a system API, an integration with your company's hardware. Putting it in your app's main file works, but turning it into a plugin gives you a clean boundary, its own permissions, and the option to share it between projects or publish it.

In this lesson you will scaffold a plugin, give it commands and state, understand how its permissions are generated, and write the JavaScript wrapper. You should already be comfortable with the plugin flow from The Tauri Plugin System.

Real versus stand-in. The Rust, TOML, JSON and TypeScript below are real Tauri 2 code to read. The runnable blocks model the plugin builder pattern in JavaScript so you can see how setup, state and commands fit together. They are not Tauri.

Scaffolding

The CLI generates a complete plugin project, with the Rust crate, the npm package, a permissions folder and an example app:

Terminal
npx @tauri-apps/cli plugin new counter
cd tauri-plugin-counter

You get roughly this layout:

TEXT
tauri-plugin-counter/
  Cargo.toml
  build.rs               # lists the commands so permissions can be generated
  src/
    lib.rs               # plugin builder and init()
    commands.rs          # command functions
    models.rs, error.rs  # data types and errors
  permissions/           # generated allow-/deny- files live here
  guest-js/index.ts      # the typed JavaScript API
  package.json
  examples/tauri-app/    # a demo app that uses the plugin

Plugin names are lowercase with hyphens. The crate is named tauri-plugin-<name> and the npm package tauri-plugin-<name>-api (or your own scope).

The plugin builder

A plugin is a value built with tauri::plugin::Builder. It declares a name, a list of commands, and optional hooks. In src/lib.rs:

Rust
use std::sync::Mutex;
use tauri::{plugin::{Builder, TauriPlugin}, Manager, Runtime};

mod commands;

#[derive(Default)]
pub struct CounterState(pub Mutex<i64>);

pub fn init<R: Runtime>() -> TauriPlugin<R> {
    Builder::new("counter")
        .invoke_handler(tauri::generate_handler![
            commands::increment,
            commands::current,
            commands::reset,
        ])
        .setup(|app, _api| {
            app.manage(CounterState::default());
            Ok(())
        })
        .build()
}

The setup hook runs once when the app starts. app.manage(...) stores a value that every command can ask for. Wrapping it in a Mutex makes it safe for several commands running at the same time on different threads.

Commands

In src/commands.rs:

Rust
use tauri::{command, AppHandle, Emitter, Runtime, State};
use crate::CounterState;

#[command]
pub fn increment<R: Runtime>(app: AppHandle<R>, state: State<'_, CounterState>, by: i64) -> Result<i64, String> {
    if by == 0 || by.abs() > 1000 {
        return Err("by must be between -1000 and 1000, and not 0".into());
    }
    let mut value = state.0.lock().map_err(|_| "state poisoned".to_string())?;
    *value += by;
    let _ = app.emit("counter://changed", *value); // event for the frontend
    Ok(*value)
}

#[command]
pub fn current(state: State<'_, CounterState>) -> i64 {
    *state.0.lock().unwrap()
}

#[command]
pub fn reset(state: State<'_, CounterState>) {
    *state.0.lock().unwrap() = 0;
}

Notice three habits that matter for real plugins: validate arguments, return Result with a clear error instead of panicking, and emit events so the UI can react without polling. Commands and events are explained in depth in the Commands and Events chapter of this track.

Permissions

A command is unreachable until a permission allows it. In a plugin, build.rs lists the commands and Tauri generates allow-<command> and deny-<command> permissions for each one:

Rust
const COMMANDS: &[&str] = &["increment", "current", "reset"];

fn main() {
    tauri_plugin::Builder::new(COMMANDS).build();
}

You then add a hand-written default set in permissions/default.toml, so a user can write counter:default and get the safe commands only:

TOML
"$schema" = "schemas/schema.json"

[default]
description = "Allows reading the counter and incrementing it"
permissions = ["allow-increment", "allow-current"]

reset is deliberately not in the default set. An app that wants it grants counter:allow-reset explicitly. Think about which commands are harmless and which are dangerous when you design the default.

You can also define a scope, a set of allowed values attached to a permission, such as a list of allowed folders. See Scopes and Input Validation.

The JavaScript API

The wrapper in guest-js/index.ts hides the plugin:counter|... command names behind normal functions:

TypeScript
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';

export async function increment(by = 1): Promise<number> {
  return await invoke<number>('plugin:counter|increment', { by });
}

export async function current(): Promise<number> {
  return await invoke<number>('plugin:counter|current');
}

export async function onChanged(handler: (value: number) => void): Promise<UnlistenFn> {
  return await listen<number>('counter://changed', (event) => handler(event.payload));
}

An app then installs the plugin with .plugin(tauri_plugin_counter::init()), adds "counter:default" to its capability, and calls import { increment } from 'tauri-plugin-counter-api'.

A runnable model of the builder

The stand-in recreates the plugin builder with setup, shared state, command validation and an event hook, so you can see how the parts fit.

Node.js Stand-in: the plugin builder, state and events

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.

Mobile code and cfg gates

If your plugin needs Android or iOS APIs, you write a Kotlin class (extending Plugin) and a Swift class, and the Rust side registers them with api.register_android_plugin(...) and api.register_ios_plugin(...) inside setup. Calls from Rust then go through PluginHandle::run_mobile_plugin. Desktop-only code should be gated with #[cfg(desktop)] and mobile-only with #[cfg(mobile)] so the crate compiles everywhere. See Mobile Development.

Testing and publishing

  • Run the example app in examples/tauri-app with npm run tauri dev to try your plugin end to end.
  • Unit-test command logic by putting it in plain functions that do not need a running app.
  • Publish the crate to crates.io and the guest package to npm, with matching versions, and document the exact permissions your plugin offers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you store data that several plugin commands need to share?

    app.manage stores a typed value, and commands receive it through State<T>. Use a Mutex when it must change.
  2. 2. Which file lists the commands so Tauri can generate allow-/deny- permissions?

    tauri_plugin::Builder::new(COMMANDS).build() in build.rs generates the permission files.
  3. 3. Why leave a dangerous command such as reset out of the default permission set?

    A narrow default follows least privilege: apps that need the risky command grant it knowingly.
  4. 4. What is the command name the JavaScript wrapper uses for a plugin command called increment in plugin counter?

    All plugin commands are addressed as plugin:<name>|<command>.

Summary

  • tauri plugin new scaffolds a crate, an npm package, permissions and an example app.
  • The Builder declares the name, command handlers and a setup hook; app.manage shares state.
  • build.rs generates allow-/deny- permissions; a hand-written default set should stay minimal.
  • A small TypeScript wrapper hides the plugin:name|command strings and exposes typed functions and event listeners.
  • Validate arguments, return errors instead of panicking and gate platform code with cfg.

Next: The Tauri Security Model