Which route fits a MonoGame game?
Plain .NET. MonoGame 3.8.4 runs on .NET, so System.Net.Http.HttpClient is your HTTP client and System.Text.Json builds the body. HttpClient.SendAsync() does not block and does not throw for a 4xx or 5xx response, so the code reads the status code.
The Analytics class below has no MonoGame types in it. The game calls Update() once per frame. That method checks whether the send task is done, so no callback touches game state from another thread.
Sources: MonoGame documentation, What is new and Game class; Microsoft .NET documentation, HttpClient.SendAsync and Guid.NewGuid.
What must every MonoGame 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 MonoGame?
Add this class to your game project. It keeps one static HttpClient, because Microsoft advises against a new client for each request. The queue is one event JSON per line in queue.txt. The timestamp format quotes the : and - separators and uses CultureInfo.InvariantCulture, so every player culture gives the same Z form.
The class builds JSON with JsonObject, not with reflection based JsonSerializer calls, which Microsoft marks as needing dynamic code. That keeps it safe for iOS, which compiles ahead of time.
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, Custom date and time format strings, Use a JSON DOM and Environment.SpecialFolder.
How do I connect the class to the game loop?
Create the class in Initialize(). In MonoGame 3.8.4, Exiting is an EventHandler<ExitingEventArgs>, and Deactivated fires when the game loses focus. Queue session_end on Exiting; the queue is on disk, so the next launch sends it.
Track gameplay with analytics.Track("level_complete", new JsonObject { ["level"] = 3, ["score"] = 1200 }). Call analytics.SetConsent(true) or SetConsent(false) from your consent screen.
C# (Game1.cs)
// Game1.cs
Analytics analytics;
protected override void Initialize()
{
analytics = new Analytics();
Exiting += (sender, args) => analytics.EndSession();
Deactivated += (sender, args) => analytics.Update();
base.Initialize();
}
protected override void Update(GameTime gameTime)
{
analytics.Update();
// Consent screen: analytics.SetConsent(true);
// Gameplay: analytics.Track("level_complete", new JsonObject { ["level"] = 3, ["attempt"] = 1, ["score"] = 1200 });
base.Update(gameTime);
}Sources: MonoGame documentation, Game class and ExitingEventArgs; MonoGame source, Game.cs at v3.8.4.
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. The folder is YourGame inside LocalApplicationData, which Microsoft describes as the folder for application data of the current, non-roaming user. queue.txt 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, mobile and console builds?
The MonoGame platforms page lists WindowsDX, DesktopGL (Windows, macOS and Linux), Android and iOS, plus consoles for registered developers. 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.
- Android: add the INTERNET permission to AndroidManifest.xml. The archived Xamarin docs from Microsoft say debug builds add it for you and release builds do not, so test a release build on a device. Android 9 and later also block cleartext HTTP, so use an https:// endpoint.
- iOS: use an https:// endpoint and keep the JsonObject approach for ahead of time compilation.
- Consoles: platform rules for network access and user consent come from each console program, so check them there.
Sources: MonoGame documentation, Supported platforms; Microsoft documentation, Android INTERNET permission; Android developer documentation, Network security configuration; Manalens app events documentation.
What are the MonoGame gotchas?
Most of these come from .NET, not from MonoGame.
- 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. Some cultures give a timestamp the collector refuses, which fails the whole batch with 400. Quote the separators and pass CultureInfo.InvariantCulture.
- An Android release build without the INTERNET permission cannot connect, even though the debug build worked.
- Exiting takes ExitingEventArgs in MonoGame 3.8.4. Samples written for EventHandler<EventArgs> do not compile.
- HttpClient.Timeout is 100 seconds by default. The class sets 15 seconds, so a stuck request does not hold the queue for long.
Sources: Microsoft .NET documentation, HttpClient guidelines, Custom date and time format strings and HttpClientJsonExtensions; Microsoft documentation, Android INTERNET permission; MonoGame source, Game.cs at v3.8.4.
How do I check that MonoGame events arrive?
Send one batch from a development build and read the response status. Set a breakpoint after the send task completes in Update(): the status should be 200.
- Create a test project in Manalens and copy its Publishable key.
- Run the DesktopGL or WindowsDX project in Debug with a test Publishable key and give consent.
- Send game_open and session_start from the MonoGame build, then check that the response is {"accepted":2}.
- Open the activity feed and check that platform, build and engine are set on the events.
- Switch off the network, play for a minute, switch it on, and check that the queued events arrive once.
- 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 Analytics.cs to your MonoGame project, ask for consent, and use the Game KPIs board to compare retention between builds and platforms.
Sources: Manalens product documentation.
Frequently asked questions
Does MonoGame have built-in analytics?
No. MonoGame has no analytics or HTTP API, but it runs on .NET, so HttpClient can post events to /v0/events with your Publishable key. Poll the send task in Game.Update(), keep the queue in a file in LocalApplicationData, and use Guid.NewGuid() for the player ID.
Is Guid.NewGuid() a valid anonymous ID?
Yes. Microsoft documents that Guid.NewGuid() creates a version 4 UUID as described in RFC 4122. The collector checks the version digit of anonymous_id and message_id, so a Guid in its default string form passes. Create the anonymous ID once, save it, and reuse it on every launch.
Why does my MonoGame Android release build send nothing?
Most likely the INTERNET permission is missing. The archived Xamarin docs from Microsoft say debug builds add it for you and release builds do not. Add it to AndroidManifest.xml and use an https:// endpoint, because Android 9 and later block cleartext HTTP by default.
Can a MonoGame game send events from a web build?
Not today. The MonoGame platforms page lists Windows, macOS, Linux, Android, iOS and consoles for registered developers, and no web target. If you need a browser version of your game, it needs its own sender with fetch() and the CORS rules of the collector.
Sources and implementation
- MonoGame documentation: Game class (read 18 November 2026) ↗
- MonoGame documentation: Supported platforms (read 18 November 2026) ↗
- MonoGame documentation: What is new (read 18 November 2026) ↗
- Microsoft .NET documentation: HttpClient.SendAsync (read 18 November 2026) ↗
- Microsoft .NET documentation: HttpClient guidelines (read 18 November 2026) ↗
- Microsoft .NET documentation: Guid.NewGuid (read 18 November 2026) ↗
- Microsoft .NET documentation: Custom date and time format strings (read 18 November 2026) ↗
- Microsoft documentation: Android INTERNET permission (Xamarin, archived) (read 18 November 2026) ↗