Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Commands and Events

Channels: Streaming Data from Rust to the Frontend

Stream ordered, fast messages from Rust to JavaScript with Tauri channels: the Channel type, onmessage, typed enums, download progress, binary data and channels versus events.

Events work well for occasional notifications, but they are broadcast, unordered in practice and not built for heavy traffic. When a command must send many ordered messages to one caller, such as download progress, log lines or chunks of a file, Tauri has channels.

Channel versus event

Event Channel
Audience Any listener, any window The one caller that created it
Ordering Not guaranteed to be strict Messages arrive in order
Throughput Light Designed for fast streams
Setup Name + listener Passed as a command argument
Cleanup You must unlisten Ends with the command's context

Tauri uses channels internally for streaming data such as child process output and download progress.

The Rust side

A command takes a tauri::ipc::Channel<T> parameter. T is the message type, usually an enum so one channel can carry several kinds of messages.

Rust
use serde::Serialize;
use tauri::ipc::Channel;

#[derive(Clone, Serialize)]
#[serde(tag = "event", content = "data", rename_all = "camelCase")]
enum DownloadEvent {
    Started { url: String, total_bytes: u64 },
    Progress { downloaded: u64 },
    Finished,
}

#[tauri::command]
async fn download(url: String, on_event: Channel<DownloadEvent>) -> Result<(), String> {
    let total = 4_000u64;
    on_event.send(DownloadEvent::Started { url, total_bytes: total }).map_err(|e| e.to_string())?;

    let mut downloaded = 0;
    while downloaded < total {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        downloaded += 1_000;
        on_event.send(DownloadEvent::Progress { downloaded }).map_err(|e| e.to_string())?;
    }

    on_event.send(DownloadEvent::Finished).map_err(|e| e.to_string())?;
    Ok(())
}

send returns a Result; it fails if the frontend side is gone. The argument name on_event is onEvent in JavaScript.

The JavaScript side

Create a Channel, set its onmessage handler and pass it in the arguments:

TypeScript
import { invoke, Channel } from "@tauri-apps/api/core";

type DownloadEvent =
  | { event: "started"; data: { url: string; totalBytes: number } }
  | { event: "progress"; data: { downloaded: number } }
  | { event: "finished" };

const onEvent = new Channel<DownloadEvent>();
onEvent.onmessage = (message) => {
  switch (message.event) {
    case "started": console.log("total", message.data.totalBytes); break;
    case "progress": console.log("downloaded", message.data.downloaded); break;
    case "finished": console.log("done"); break;
  }
};

await invoke("download", { url: "https://example.com/file.zip", onEvent });

The invoke Promise resolves when the command returns, after all messages were sent. Handle messages in onmessage and use the final result for success or failure.

A handy detail: messages are delivered in the order they were sent, even though the handler runs asynchronously on the JavaScript side.

Sending bytes

Channels can also carry raw binary data using tauri::ipc::InvokeResponseBody (or Channel<&[u8]>-like patterns through that type); the JavaScript onmessage then receives an ArrayBuffer. Use this for file chunks or image frames instead of JSON arrays of numbers, which are very slow and large.

Rust
use tauri::ipc::{Channel, InvokeResponseBody};

#[tauri::command]
fn stream_file(path: String, reader: Channel<InvokeResponseBody>) -> Result<(), String> {
    let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
    for chunk in bytes.chunks(8192) {
        reader.send(InvokeResponseBody::Raw(chunk.to_vec())).map_err(|e| e.to_string())?;
    }
    Ok(())
}

The same advice holds for command return values: returning a Vec<u8> serializes to a huge JSON array. For big binary results, use tauri::ipc::Response to send raw bytes.

Patterns that work well

  • Progress bars. Send Progress { done, total } messages, compute the percentage in the frontend.
  • Log tailing. Send each new line as a message.
  • Search results. Send batches as they are found so the UI fills in progressively.
  • Cancel. Pair the channel with a cancel command and an atomic flag like in Async commands.
sequenceDiagram
  participant JS as Frontend
  participant R as Rust command
  JS->>R: invoke("download", { onEvent: channel })
  R-->>JS: Started
  R-->>JS: Progress 1000
  R-->>JS: Progress 2000
  R-->>JS: Finished
  R-->>JS: Promise resolves

One call, many ordered messages, then the final result.

Try it: a channel stand-in

The stand-in models the contract: a Channel object with onmessage, a command that sends a tagged stream, and an invoke that resolves after the stream ends.

Node.js Stand-in: stream with a Channel

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: render a progress bar from messages (stand-in)

Here the handler turns progress messages into a text progress bar, the way a UI would update a <progress> element.

Node.js Stand-in: a progress bar from channel messages

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.

Which should I use?

  • A single "it finished" signal: an event, or just the command's return value.
  • Progress or output for one specific call: a channel.
  • Something every window should know: an event.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a channel best used for?

    Channels deliver ordered streams to the one frontend caller that passed it.
  2. 2. How does JavaScript receive channel messages?

    You create new Channel(), set onmessage and pass it as an argument to invoke.
  3. 3. Why use an enum as the channel message type?

    A tagged enum becomes a discriminated union on the JavaScript side.
  4. 4. How should you send a large binary chunk?

    Raw byte responses avoid the size and speed cost of JSON arrays.

Summary

  • Channels stream ordered messages from a command back to its caller.
  • Take a Channel<T> parameter in Rust; create new Channel() with onmessage in JavaScript.
  • Use a tagged enum for several message kinds.
  • Send binary data as raw bytes, not as JSON arrays.
  • Use events for broadcast notifications, channels for per-call streams.

Next: Windows