# How to add analytics to a Stride game

> Track a Stride game with .NET HttpClient: a SyncScript that polls the send task, a saved Guid player ID, a file queue with retries, consent and Android notes.

By Yos Riady. Updated 2026-11-18. Published 2026-11-18. Canonical URL: https://manalens.dev/blog/stride-analytics

Stride has no HTTP or analytics API, so use .NET HttpClient to post events to /v0/events, up to 50 per request, and poll the send task from a SyncScript. The Stride manual warns that Task.Run runs your code on the thread pool instead of the main thread, so do not use it in scripts. Keep the queue in LocalApplicationData.

## Key points

- Stride games are .NET programs, so post events with HttpClient and poll the send task from a SyncScript every frame on the main thread.
- Do not use Task.Run for Stride analytics code that touches game state, because the Stride manual says it runs on the thread pool.
- Put the Stride analytics script on an entity that stays loaded, because a script on a level entity stops when its scene unloads.

## Which route fits a Stride game?

Plain .NET in a script. Stride 4.4 games are .NET programs, so System.Net.Http.HttpClient sends the request and System.Text.Json builds the body. The Analytics class below has no Stride types in it; a small SyncScript calls its Update() method every frame on the main thread.

Polling a Task from Update() keeps all game state on the main thread. The Stride manual says Task.Run runs code on the thread pool, not on the main thread, and points to Script.AddTask() for work that must stay in the script system.

Sources: Stride manual, Types of script and Asynchronous scripts; Stride API, ScriptSystem; Microsoft .NET documentation, HttpClient.SendAsync.

## What must every Stride 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 Stride?

Add this class to your game project. It keeps one static HttpClient, builds JSON with JsonObject, and writes the timestamp with CultureInfo.InvariantCulture so every player culture gives the Z form. Guid.NewGuid() creates a version 4 UUID, Microsoft documents, which is the format the collector checks.

``` C# (Analytics.cs)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

public sealed class Analytics
{
    const string Url = "https://YOUR_COLLECTOR_ENDPOINT/v0/events";
    const string Key = "YOUR_PUBLISHABLE_KEY";
    static readonly HttpClient Http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
    readonly string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YourGame");
    readonly List<string> queue = new();
    readonly string sessionId = Guid.NewGuid().ToString();
    readonly DateTime startedAt = DateTime.UtcNow;
    string anonId; bool consent; Task<int> inflight; int inflightCount; DateTime nextSend; double backoff;

    string P(string f) => Path.Combine(dir, f);
    static string Now() => DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", CultureInfo.InvariantCulture);
    static string Platform() => OperatingSystem.IsAndroid() ? "android" : OperatingSystem.IsIOS() ? "ios"
        : OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : OperatingSystem.IsLinux() ? "linux" : "other";

    public Analytics()
    {
        if (!File.Exists(P("consent"))) return;
        if (File.Exists(P("queue.txt"))) queue.AddRange(File.ReadAllLines(P("queue.txt")));
        SetConsent(true);
    }

    public void SetConsent(bool on)
    {
        consent = on;
        if (!on)
        {
            anonId = null; queue.Clear();
            if (Directory.Exists(dir)) foreach (var f in new[] { "consent", "anon_id", "queue.txt" }) File.Delete(P(f));
            return;
        }
        Directory.CreateDirectory(dir);
        File.WriteAllText(P("consent"), "1");
        bool first = !File.Exists(P("anon_id"));
        if (first) File.WriteAllLines(P("anon_id"), new[] { Guid.NewGuid().ToString(), Now() });
        var lines = File.ReadAllLines(P("anon_id"));
        anonId = lines[0];
        Track("game_open", new JsonObject { ["is_first_open"] = first, ["first_open_at"] = lines[1] });
        Track("session_start", new JsonObject());
    }

    public void Track(string evt, JsonObject props)
    {
        if (!consent || anonId == null) return;
        var e = new JsonObject
        {
            ["type"] = "track", ["event"] = evt, ["channel"] = "app", ["version"] = "0.1.0",
            ["message_id"] = Guid.NewGuid().ToString(), ["anonymous_id"] = anonId, ["session_id"] = sessionId,
            ["original_timestamp"] = Now(),
            ["context"] = new JsonObject
            {
                ["app"] = new JsonObject { ["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
        };
        queue.Add(e.ToJsonString());
        Save();
    }

    public void EndSession() => Track("session_end", new JsonObject { ["duration_s"] = (int)(DateTime.UtcNow - startedAt).TotalSeconds });
    void Save() { if (consent) File.WriteAllLines(P("queue.txt"), queue); }

    // Call once per frame from the game thread.
    public void Update()
    {
        if (inflight != null)
        {
            if (!inflight.IsCompleted) return;
            int s = inflight.IsCompletedSuccessfully ? inflight.Result : 0;
            inflight = null;
            if ((s >= 200 && s < 300) || (s >= 400 && s < 500 && s != 408 && s != 429))
            {
                queue.RemoveRange(0, Math.Min(inflightCount, queue.Count));
                backoff = 0; nextSend = DateTime.UtcNow; Save();
            }
            else { backoff = Math.Clamp(backoff * 2, 5, 300); nextSend = DateTime.UtcNow.AddSeconds(backoff); }
            return;
        }
        if (!consent || queue.Count == 0 || DateTime.UtcNow < nextSend) return;
        inflightCount = Math.Min(50, queue.Count);
        inflight = Send("{\"events\":[" + string.Join(",", queue.GetRange(0, inflightCount)) + "]}");
        nextSend = DateTime.UtcNow.AddSeconds(10);
    }

    static async Task<int> Send(string body)
    {
        try
        {
            using var req = new HttpRequestMessage(HttpMethod.Post, Url) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
            req.Headers.Add("x-publishable-key", Key);
            using var res = await Http.SendAsync(req);
            return (int)res.StatusCode;
        }
        catch (Exception) { return 0; }
    }
}
```

Sources: Microsoft .NET documentation, HttpClient guidelines, Guid.NewGuid, Custom date and time format strings and Environment.SpecialFolder.

## How do I connect the class to a Stride script?

Add AnalyticsScript to an entity that stays loaded for the whole game. A script runs only while its entity is in the scene, so a script on a level entity stops when the level unloads. IGame has Exiting and Deactivated events; the script queues session_end on Exiting, and the next launch sends it.

``` C# (AnalyticsScript.cs)
using Stride.Engine;
using System.Text.Json.Nodes;

// Add this script to an entity that stays loaded for the whole game.
public class AnalyticsScript : SyncScript
{
    public static Analytics Instance { get; private set; }

    public override void Start()
    {
        Instance ??= new Analytics();
        Game.Exiting += (sender, args) => Instance.EndSession();
        Game.Deactivated += (sender, args) => Instance.Update();
    }

    public override void Update() => Instance.Update();
}

// Consent screen: AnalyticsScript.Instance.SetConsent(true);
// Gameplay:
// AnalyticsScript.Instance.Track("level_complete", new JsonObject { ["level"] = 3, ["attempt"] = 1, ["score"] = 1200 });
```

Sources: Stride manual, Types of script; Stride API, IGame and ScriptComponent.

## How do the player ID, the offline queue and consent work?

The anonymous_id is a Guid in the file anon_id, with the first open time on its second line, in a YourGame folder inside LocalApplicationData. queue.txt holds one event JSON per line and is rewritten on every Track() call, so a crash or an offline session loses nothing.

Keep the batch and wait longer before each retry after a network error or a 5xx, 408 or 429 response. Drop it after any other 4xx, because the collector refused the data and a retry gets the same answer. That also clears a batch with an event older than 7 days, which the collector refuses with 400.

Until consent, Track() does nothing and no ID file exists. SetConsent(false) deletes the files. Whether your game needs consent is a decision for you and your legal advisers.

Sources: Microsoft .NET documentation, Environment.SpecialFolder; Manalens app events documentation.

## What changes for desktop and mobile builds?

The Stride platforms page lists Windows, Linux, macOS, Android and iOS. It lists no web target, so there is no HTML5 build to plan for.

- Desktop: HttpClient sends no Origin header, so CORS does not apply and the collector accepts the request with the Publishable key alone.
- Editor: Game Studio runs natively only on Windows. On macOS and Linux you build from code.
- Android: the Stride manual says Android is no longer experimental since 4.4, but that few people look after it. Test the network on a device, declare the INTERNET permission, and use an https:// endpoint, because Android 9 and later block cleartext HTTP by default.
- iOS: use an https:// endpoint and keep the JsonObject approach for ahead of time compilation.

Sources: Stride manual, Platforms, Android and Release notes; Android developer documentation, Network security configuration; Manalens app events documentation.

## What are the Stride gotchas?

Most of these come from the script system and from .NET.

- Do not start the send with Task.Run() and touch game state in its continuation. The manual says Task.Run code runs on the thread pool, not on the main thread. Poll the task in Update(), or use Script.AddTask().
- A script on a level entity stops, and its Cancel() runs, when the scene unloads. Put the analytics script on an entity that stays loaded.
- A new HttpClient for each request can use up sockets. Keep one static client.
- DateTime.ToString("HH:mm:ss") uses the time separator of the player culture. Quote the separators and pass CultureInfo.InvariantCulture, or some players send timestamps that fail the whole batch with 400.
- HttpClient.Timeout is 100 seconds by default. The class sets 15 seconds, so a stuck request does not hold the queue for long.

Sources: Stride manual, Asynchronous scripts, Types of script, Platforms and Android; Microsoft .NET documentation, HttpClient guidelines and Custom date and time format strings.

## How do I check that Stride events arrive?

Send one batch from a development build and read the response status. Set a breakpoint after the send task completes in Analytics.Update(): the status should be 200.

1. Create a test project in Manalens and copy its Publishable key.
2. Run the Windows game project from Game Studio or your IDE with a test Publishable key and give consent.
3. Send game_open and session_start from the Stride 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 class and the script to your Stride project, ask for consent, and use the Game KPIs board to see retention and session length for each build.

- [All installation options](https://manalens.dev/docs/install)

Sources: Manalens product documentation.

## Frequently asked questions

### Does Stride have built-in analytics?

No. Stride has no analytics or HTTP API, but Stride games are .NET programs, so HttpClient can post events to /v0/events with your Publishable key. Poll the send task from a SyncScript every frame, keep the queue in a file, and use Guid.NewGuid() for the player ID.

### Can I use Task.Run for analytics in Stride?

Not for code that touches game state. The Stride manual says Task.Run runs your code on the thread pool instead of the main thread. HttpClient.SendAsync() already does not block, so start it from the script and check the task in Update(), or use Script.AddTask() for script work.

### Why did my Stride analytics stop after a level change?

Because a script runs only while its entity is in the scene. If the analytics script sits on a level entity, it stops and Cancel() runs when that scene unloads. Put it on an entity that stays loaded for the whole game, and keep the Analytics instance in a static property.

### Does Stride have a web export?

No. The Stride platforms page lists Windows, Linux, macOS, Android and iOS, and no web target. So the Stride code needs no CORS setup: a native HttpClient request sends no Origin header, and the collector accepts it with the Publishable key alone.

## Sources

- [Stride manual: Types of script (read 18 November 2026)](https://doc.stride3d.net/latest/en/manual/scripts/types-of-script/index.html)
- [Stride manual: Asynchronous scripts (read 18 November 2026)](https://doc.stride3d.net/4.3/en/manual/scripts/types-of-script/async-script.html)
- [Stride API: ScriptSystem (read 18 November 2026)](https://doc.stride3d.net/latest/en/api/Stride.Engine.Processors.ScriptSystem.html)
- [Stride API: IGame (read 18 November 2026)](https://doc.stride3d.net/latest/en/api/Stride.Games.IGame.html)
- [Stride manual: Platforms (read 18 November 2026)](https://doc.stride3d.net/latest/en/manual/platforms/)
- [Stride manual: Android (read 18 November 2026)](https://doc.stride3d.net/latest/en/manual/platforms/android/index.html)
- [Stride release notes (read 18 November 2026)](https://doc.stride3d.net/latest/en/ReleaseNotes/)
- [Microsoft .NET documentation: HttpClient.SendAsync (read 18 November 2026)](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync)
- [Microsoft .NET documentation: Guid.NewGuid (read 18 November 2026)](https://learn.microsoft.com/en-us/dotnet/api/system.guid.newguid)

## Related guides

- [Game marketing measurement guide](https://manalens.dev/blog/game-marketing-measurement-guide)
- [Engine analytics compared: Unreal, Godot, GameMaker, Construct, Phaser](https://manalens.dev/blog/game-engine-analytics-compared)
- [How to add analytics to a MonoGame game](https://manalens.dev/blog/monogame-analytics)
- [How to add analytics to an Unreal Engine game](https://manalens.dev/blog/unreal-engine-analytics)
- [What events to track first in your game](https://manalens.dev/blog/game-tracking-plan-first-events)
- [Player analytics guides](https://manalens.dev/blog/topic/player-analytics)
- [How to move from GameAnalytics to Manalens](https://manalens.dev/blog/migrate-from-gameanalytics)
- [How to add analytics to a Raylib game](https://manalens.dev/blog/raylib-analytics)
- [How to add analytics to a LÖVE (Love2D) game](https://manalens.dev/blog/love2d-analytics)
- [How to add analytics to a Godot game](https://manalens.dev/blog/godot-analytics)
