Which route fits a Bevy game?

A Bevy plugin with a blocking HTTP crate on a task pool. ureq 3 is a small blocking client: agent.post(url).header(name, value).send(body). The plugin spawns that call on IoTaskPool, keeps the Task in a resource, and checks it once per frame with bevy::tasks::futures::check_ready(), which returns None until the task is done.

The official Bevy async_compute example warns against future::block_on(poll_once(task)), because it is expensive and can block the main thread. Older tutorials still use it.

Sources: Bevy documentation, IoTaskPool, Task and check_ready; Bevy example, async_compute; ureq documentation.

What must every Bevy event contain?

One JSON envelope, the same one the Godot and Unity SDKs send. POST it to /v0/events on your collector with two headers: x-publishable-key and Content-Type: application/json. The body is {"events": [...]} with 1 to 50 events. A good request returns {"accepted":N}.

  • type "track", an event name in snake_case, channel "app" and version (your tracker version, up to 32 characters).
  • message_id: a new UUID version 4 for each event. Keep it on a retry. The collector counts each message_id once.
  • anonymous_id: one UUID version 4 per install, saved on the device. The collector checks the version digit, so a random hex string of the same length is refused.
  • session_id: 1 to 64 characters of letters, digits and . _ : -. Start a new one after 30 minutes without play.
  • original_timestamp: the time of the event in ISO 8601 UTC, such as 2026-11-09T10:00:00Z. It can be up to 7 days old, and at most 10 minutes in the future.
  • context.app.platform (windows, macos, linux, web, android, ios or other) and engine "other". Add storefront, app_version and build to filter reports by build.
  • properties: a flat object of strings, numbers, booleans or null.

Sources: Manalens app events documentation.

How do I send events from Bevy?

Add the crates in the first comment. uuid needs its v4 feature for Uuid::new_v4(). chrono formats the time with to_rfc3339_opts(SecondsFormat::Millis, true), which gives the Z form. directories::ProjectDirs finds the data folder for each OS.

ureq 3 returns 4xx and 5xx responses as errors by default. The agent sets http_status_as_error(false), so the code gets the status code and can tell a refused batch from a server error. timeout_global() stops a request after 15 seconds.

Rust (Bevy 0.20, src/analytics.rs)

// Cargo.toml: bevy = "0.20", ureq = "3", serde_json = "1", chrono = "0.4",
// uuid = { version = "1", features = ["v4"] }, directories = "6"
use bevy::app::AppExit;
use bevy::ecs::message::MessageReader;
use bevy::prelude::*;
use bevy::tasks::{futures::check_ready, IoTaskPool, Task};
use serde_json::{json, Value};
use std::{fs, path::PathBuf, time::Duration};
use uuid::Uuid;

const URL: &str = "https://YOUR_COLLECTOR_ENDPOINT/v0/events";
const KEY: &str = "YOUR_PUBLISHABLE_KEY";

#[derive(Resource)]
pub struct Analytics {
    dir: PathBuf, consent: bool, anon_id: Option<String>, session_id: String, queue: Vec<Value>,
    inflight: Option<(usize, Task<Option<u16>>)>, next_at: f32, backoff: f32,
}

fn now() -> String { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) }

impl Analytics {
    fn load() -> Self {
        let dir = directories::ProjectDirs::from("com", "YourStudio", "YourGame")
            .map(|d| d.data_local_dir().to_path_buf()).unwrap_or_else(|| PathBuf::from("."));
        let anon_id = fs::read_to_string(dir.join("anon_id")).ok();
        let queue = fs::read_to_string(dir.join("queue.json")).ok()
            .and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
        Self { consent: dir.join("consent").exists(), dir, anon_id, queue, session_id: Uuid::new_v4().to_string(),
               inflight: None, next_at: 0.0, backoff: 0.0 }
    }
    pub fn set_consent(&mut self, on: bool) {
        self.consent = on;
        if !on {
            for f in ["consent", "anon_id", "first_open_at", "queue.json"] { let _ = fs::remove_file(self.dir.join(f)); }
            self.anon_id = None; self.queue.clear(); return;
        }
        let _ = fs::create_dir_all(&self.dir);
        let _ = fs::write(self.dir.join("consent"), "1");
        let first = self.anon_id.is_none();
        if first {
            let id = Uuid::new_v4().to_string();
            let _ = fs::write(self.dir.join("anon_id"), &id);
            let _ = fs::write(self.dir.join("first_open_at"), now());
            self.anon_id = Some(id);
        }
        let first_at = fs::read_to_string(self.dir.join("first_open_at")).ok();
        self.track("game_open", json!({ "is_first_open": first, "first_open_at": first_at }));
        self.track("session_start", json!({}));
    }
    pub fn track(&mut self, event: &str, props: Value) {
        let Some(anon) = self.anon_id.clone().filter(|_| self.consent) else { return };
        let os = std::env::consts::OS;
        let platform = if ["windows", "macos", "linux", "android", "ios"].contains(&os) { os } else { "other" };
        self.queue.push(json!({ "type": "track", "event": event, "channel": "app", "version": "0.1.0",
            "message_id": Uuid::new_v4().to_string(), "anonymous_id": anon, "session_id": self.session_id,
            "original_timestamp": now(),
            "context": { "app": { "platform": platform, "storefront": "steam", "app_version": "1.4.0",
                "build": "571", "engine": "other" }, "locale": "en", "library_name": "my-game", "library_version": "1.4.0" },
            "properties": props }));
        self.save();
    }
    fn save(&self) {
        if self.consent { let _ = fs::write(self.dir.join("queue.json"), serde_json::to_string(&self.queue).unwrap_or_default()); }
    }
}

fn send(body: String) -> Option<u16> {
    let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false)
        .timeout_global(Some(Duration::from_secs(15))).build().into();
    let res = agent.post(URL).header("x-publishable-key", KEY)
        .header("Content-Type", "application/json").send(body.as_str()).ok()?;
    Some(res.status().as_u16())
}

fn flush(mut a: ResMut<Analytics>, time: Res<Time>) {
    let a = &mut *a;
    let now_s = time.elapsed_secs();
    if let Some((n, task)) = &mut a.inflight {
        let Some(status) = check_ready(task) else { return };
        let n = (*n).min(a.queue.len());
        a.inflight = None;
        match status {
            Some(s) if (200..300).contains(&s) || ((400..500).contains(&s) && s != 408 && s != 429) => {
                a.queue.drain(..n); a.backoff = 0.0; a.save();
            }
            _ => { a.backoff = (a.backoff * 2.0).clamp(5.0, 300.0); a.next_at = now_s + a.backoff; }
        }
        return;
    }
    if !a.consent || a.queue.is_empty() || now_s < a.next_at { return; }
    let n = a.queue.len().min(50);
    let body = serde_json::to_string(&json!({ "events": &a.queue[..n] })).unwrap_or_default();
    a.inflight = Some((n, IoTaskPool::get().spawn(async move { send(body) })));
    a.next_at = now_s + 10.0;
}

fn on_exit(mut exits: MessageReader<AppExit>, mut a: ResMut<Analytics>, time: Res<Time>) {
    if exits.read().next().is_some() { a.track("session_end", json!({ "duration_s": time.elapsed_secs() as u32 })); }
}

pub struct AnalyticsPlugin;
impl Plugin for AnalyticsPlugin {
    fn build(&self, app: &mut App) {
        let mut a = Analytics::load();
        if a.consent { a.set_consent(true); }
        app.insert_resource(a).add_systems(Update, (flush, on_exit));
    }
}

Sources: Bevy documentation, IoTaskPool, check_ready, AppExit and MessageReader; ureq documentation, ConfigBuilder; uuid, chrono, serde_json and directories documentation.

How do I add the plugin and track gameplay?

Add AnalyticsPlugin to your app. Systems take ResMut<Analytics> to track events or change consent. AppExit is a message in Bevy 0.20, read with MessageReader<AppExit>, not an event read with EventReader. On exit, the plugin queues session_end, and the next launch sends it.

Use the event conventions, such as level_start, level_complete and resource, so the Game KPIs board reads them.

Rust (src/main.rs)

use bevy::prelude::*;
use serde_json::json;
mod analytics;
use analytics::{Analytics, AnalyticsPlugin};

fn main() {
    App::new()
        .add_plugins((DefaultPlugins, AnalyticsPlugin))
        .add_systems(Update, (consent_keys, level_done))
        .run();
}

// Replace with your consent screen.
fn consent_keys(keys: Res<ButtonInput<KeyCode>>, mut analytics: ResMut<Analytics>) {
    if keys.just_pressed(KeyCode::KeyY) { analytics.set_consent(true); }
    if keys.just_pressed(KeyCode::KeyN) { analytics.set_consent(false); }
}

fn level_done(mut analytics: ResMut<Analytics>, keys: Res<ButtonInput<KeyCode>>) {
    if keys.just_pressed(KeyCode::Enter) {
        analytics.track("level_complete", json!({ "level": 3, "attempt": 1, "score": 1200 }));
    }
}

Sources: Bevy documentation, AppExit, MessageReader and Plugin; Manalens app events documentation.

What changes for web, desktop and mobile builds?

The plugin as written is for native builds.

  • Windows, macOS and Linux: ureq sends no Origin header, so CORS does not apply and the collector accepts the request with the Publishable key alone.
  • Web (wasm32): ureq opens sockets and cannot run in a browser, and a Bevy web build has no file system. Gate the plugin with #[cfg(not(target_arch = "wasm32"))] and write a separate sender that uses the browser fetch API and localStorage.
  • Web CORS: a browser sends a preflight because of the x-publishable-key header. The collector answers it for your project domain, its subdomains and Allowed origins. *.itch.zone is allowed by default.
  • Android and iOS: use an https:// endpoint, because Android 9 and later block cleartext HTTP by default. std::env::consts::OS reports android or ios, so the platform field is right.

Sources: Bevy documentation, Task; ureq issue tracker; chrono documentation, Utc; Android developer documentation, Network security configuration; Manalens app events documentation.

What are the Bevy gotchas?

Most of these come from API changes between Bevy versions.

  • Dropping a Task cancels it, the Bevy docs say. Keep it in a resource or a component, as the plugin does with inflight, or call detach().
  • Do not poll tasks with block_on(poll_once(...)). Use check_ready(), as the official example now does.
  • AppExit is a message in Bevy 0.20. Code that reads it with EventReader<AppExit> from an older tutorial does not compile.
  • ureq 3 turns 4xx and 5xx into errors by default. If you match only Ok, a 400 looks like a network error, and the plugin would retry bad data forever. Set http_status_as_error(false).
  • Uuid::new_v4() exists only with the v4 feature of the uuid crate.

Sources: Bevy documentation, Task, AppExit and check_ready; Bevy example, async_compute; ureq documentation, ConfigBuilder; uuid documentation.

How do I check that Bevy events arrive?

Send one batch from a development build and read the response status. Add a debug! line with the status in the flush system while you test: 200 means the batch was accepted.

  1. Create a test project in Manalens and copy its Publishable key.
  2. Run cargo run with a test Publishable key and press Y to give consent.
  3. Send game_open and session_start from the Bevy build, then check that the response is {"accepted":2}.
  4. Open the activity feed and check that platform, build and engine are set on the events.
  5. Switch off the network, play for a minute, switch it on, and check that the queued events arrive once.
  6. Replace the test key with the production Publishable key before you ship.

Sources: Manalens app events documentation.

How do I start?

Manalens is the analytics and growth engine built for games. Add the Bevy plugin, ask for consent, and use the Game KPIs board to see retention and level fail rates for each build.

Sources: Manalens product documentation.

Frequently asked questions

Does Bevy have an HTTP client?

No. Bevy has task pools but no HTTP client, so add a crate. This guide uses ureq 3 on the IoTaskPool and checks the task each frame with check_ready(). Set http_status_as_error(false) on the ureq agent, so a 400 or 500 response gives you the status code instead of an error.

How do I run a blocking request in Bevy without freezing the game?

Spawn it on IoTaskPool::get().spawn(), keep the returned Task in a resource, and call check_ready() on it once per frame. The official async_compute example uses this pattern and warns that block_on(poll_once(task)) is expensive and can block the main thread. Dropping the Task cancels it.

How do I detect that a Bevy game is closing?

Read AppExit with MessageReader<AppExit>, because AppExit is a message in Bevy 0.20, not an event. The docs say systems that listen for it must run before the current update ends. Queue session_end there; the queue is on disk, so the next launch sends it.

Does this Bevy code work in a wasm build?

No. ureq opens sockets and cannot run in a browser, and a Bevy web build has no file system. Gate the plugin with a cfg for wasm32 and write a browser sender with fetch and localStorage. The browser then sends a CORS preflight, which the collector answers for allowed hosts.

Sources and implementation