# How to add analytics to a Raylib game

> Add analytics to a raylib game in C: libcurl on desktop, emscripten_fetch on the web, a saved player ID, a text file queue with retries and consent.

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

raylib has no network functions, so post events to /v0/events with libcurl on desktop and with emscripten_fetch() in a web build, up to 50 per request. raylib 6.2 seeds its random generator with time(NULL) in InitWindow() (raylib source), so add more entropy before you make a player ID. Keep the queue in a text file.

## Key points

- raylib has no network functions, so send events with libcurl on desktop and with emscripten_fetch() in a web build linked with -sFETCH.
- Re-seed the raylib random generator after InitWindow(), because raylib 6.2 seeds with time(NULL) and players who start in the same second share IDs.
- In a shipped raylib game, run Flush() on a worker thread or use the libcurl multi interface, because curl_easy_perform() can stall the frame.

## Which route fits a raylib game?

libcurl for desktop builds. raylib covers windows, input, graphics and audio, and nothing in raylib.h sends HTTP. The libcurl easy interface does: CURLOPT_HTTPHEADER sets the two headers, CURLOPT_POSTFIELDS sets the JSON body, and CURLINFO_RESPONSE_CODE reads the status.

curl_easy_perform() returns only when the request ends. The sample calls it from the main loop every 10 seconds with a 10 second timeout, which is fine for a test. In a shipped game, move Flush() to a worker thread or use the libcurl multi interface, so a slow network never stalls a frame.

Web builds use Emscripten, where libcurl does not work. emscripten_fetch() is the Emscripten API for the same request.

Sources: libcurl documentation, CURLOPT_HTTPHEADER, CURLOPT_POSTFIELDS and CURLINFO_RESPONSE_CODE; raylib cheatsheet; Emscripten documentation, Fetch API.

## What must every Raylib 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 raylib on desktop?

Link with -lraylib -lcurl. The queue is one event JSON per line in mana_queue.txt, written with SaveFileText() and read with LoadFileText(). The ID and the first open time are in mana_id.txt; the file exists only after consent. The event JSON is built with snprintf(), so pass only safe event names and property JSON that you write yourself.

``` C (analytics part of main.c)
#include "raylib.h"
#include <curl/curl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MANALENS_URL "https://YOUR_COLLECTOR_ENDPOINT/v0/events"
#define MANALENS_KEY "YOUR_PUBLISHABLE_KEY"
#define MAXQ 1000
#if defined(_WIN32)
#define MANALENS_PLATFORM "windows"
#elif defined(__APPLE__)
#define MANALENS_PLATFORM "macos"
#else
#define MANALENS_PLATFORM "linux"
#endif
static char *q[MAXQ], anon[37], first_at[32], sess[37];
static int qn = 0, consent = 0;
static double retryAt = 0, backoff = 2;

static void Uuid4(char *o) {
    unsigned char b[16];
    for (int i = 0; i < 16; i++) b[i] = (unsigned char)GetRandomValue(0, 255);
    b[6] = (b[6] & 0x0F) | 0x40; b[8] = (b[8] & 0x3F) | 0x80;  // version 4, variant
    for (int i = 0, p = 0; i < 16; i++) p += sprintf(o + p, (i == 4 || i == 6 || i == 8 || i == 10) ? "-%02x" : "%02x", b[i]);
}
static void NowIso(char *o) { time_t t = time(NULL); strftime(o, 32, "%Y-%m-%dT%H:%M:%S.000Z", gmtime(&t)); }
static void SaveQueue(void) {
    size_t len = 1; for (int i = 0; i < qn; i++) len += strlen(q[i]) + 1;
    char *buf = calloc(len, 1);
    for (int i = 0; i < qn; i++) { strcat(buf, q[i]); strcat(buf, "\n"); }
    SaveFileText("mana_queue.txt", buf); free(buf);
}
static void Track(const char *name, const char *props) {
    if (!consent || qn >= MAXQ) return;
    char id[37], ts[32], ev[1024]; Uuid4(id); NowIso(ts);
    snprintf(ev, sizeof ev, "{\"type\":\"track\",\"event\":\"%s\",\"channel\":\"app\",\"version\":\"0.1.0\",\"message_id\":\"%s\","
        "\"anonymous_id\":\"%s\",\"session_id\":\"%s\",\"original_timestamp\":\"%s\",\"context\":{\"app\":{\"platform\":\"" MANALENS_PLATFORM "\","
        "\"storefront\":\"steam\",\"app_version\":\"1.4.0\",\"build\":\"571\",\"engine\":\"other\"},\"locale\":\"en\","
        "\"library_name\":\"my-game\",\"library_version\":\"1.4.0\"},\"properties\":%s}", name, id, anon, sess, ts, props);
    q[qn++] = strdup(ev); SaveQueue();
}
static size_t Discard(char *p, size_t s, size_t n, void *u) { (void)p; (void)u; return s * n; }
static void Flush(void) {
    if (!consent || qn == 0 || GetTime() < retryAt) return;
    int n = qn < 50 ? qn : 50; size_t len = 16;
    for (int i = 0; i < n; i++) len += strlen(q[i]) + 1;
    char *body = malloc(len); strcpy(body, "{\"events\":[");
    for (int i = 0; i < n; i++) { if (i) strcat(body, ","); strcat(body, q[i]); }
    strcat(body, "]}");
    CURL *c = curl_easy_init(); long status = 0;
    struct curl_slist *h = curl_slist_append(NULL, "Content-Type: application/json");
    h = curl_slist_append(h, "x-publishable-key: " MANALENS_KEY);
    curl_easy_setopt(c, CURLOPT_URL, MANALENS_URL);
    curl_easy_setopt(c, CURLOPT_HTTPHEADER, h);
    curl_easy_setopt(c, CURLOPT_POSTFIELDS, body);
    curl_easy_setopt(c, CURLOPT_TIMEOUT, 10L);
    curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, Discard);  // or libcurl prints the reply to stdout
    if (curl_easy_perform(c) == CURLE_OK) curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &status);
    curl_slist_free_all(h); curl_easy_cleanup(c); free(body);
    if ((status >= 200 && status < 300) || (status >= 400 && status < 500 && status != 408 && status != 429)) {
        for (int i = 0; i < n; i++) free(q[i]);
        memmove(q, q + n, (qn - n) * sizeof(char *)); qn -= n; SaveQueue(); backoff = 2;
    } else { retryAt = GetTime() + backoff; backoff = backoff < 300 ? backoff * 2 : 300; }
}
static void SetConsent(int on) {
    if (on && !consent) {
        int first = !anon[0]; consent = 1;
        if (first) { Uuid4(anon); NowIso(first_at); }
        char buf[80]; snprintf(buf, sizeof buf, "%s\n%s", anon, first_at); SaveFileText("mana_id.txt", buf);
        char p[96]; snprintf(p, sizeof p, "{\"is_first_open\":%s,\"first_open_at\":\"%s\"}", first ? "true" : "false", first_at);
        Track("game_open", p); Track("session_start", "{}");
    } else if (!on) {
        consent = 0; anon[0] = 0;
        for (int i = 0; i < qn; i++) free(q[i]);
        qn = 0; FileRemove("mana_id.txt"); FileRemove("mana_queue.txt");
    }
}
```

Sources: raylib cheatsheet, SaveFileText, LoadFileText, FileExists, FileRemove, GetRandomValue, SetRandomSeed and GetTime; libcurl documentation.

## How do I start a session and flush from the main loop?

Re-seed after InitWindow(). raylib 6.2 seeds with time(NULL), in whole seconds, so two players who start in the same second would get the same IDs. The sample mixes in a stack address and clock(); a production game can read random bytes from the operating system instead.

Code after the while (!WindowShouldClose()) loop runs on a normal close, so a last Flush() there sends what it can. The queue is on disk either way.

``` C (main.c, continued)
int main(void) {
    InitWindow(800, 450, "my game");
    int local; SetRandomSeed((unsigned)time(NULL) ^ (unsigned)(uintptr_t)&local ^ (unsigned)clock());
    curl_global_init(CURL_GLOBAL_DEFAULT);
    Uuid4(sess);
    char *t = FileExists("mana_queue.txt") ? LoadFileText("mana_queue.txt") : NULL;
    if (t) { for (char *l = strtok(t, "\n"); l && qn < MAXQ; l = strtok(NULL, "\n")) q[qn++] = strdup(l); UnloadFileText(t); }
    t = FileExists("mana_id.txt") ? LoadFileText("mana_id.txt") : NULL;
    if (t) { sscanf(t, "%36s %31s", anon, first_at); UnloadFileText(t); SetConsent(1); }
    double nextFlush = 0;
    while (!WindowShouldClose()) {
        if (IsKeyPressed(KEY_Y)) SetConsent(1);
        if (IsKeyPressed(KEY_N)) SetConsent(0);
        if (GetTime() >= nextFlush) { Flush(); nextFlush = GetTime() + 10; }
        BeginDrawing(); ClearBackground(RAYWHITE);
        DrawText(consent ? "Analytics on (N to turn off)" : "Allow analytics? Y / N", 20, 20, 20, DARKGRAY);
        EndDrawing();
    }
    Flush();
    curl_global_cleanup(); CloseWindow();
    return 0;
}
```

Sources: raylib source, rcore.c InitWindow; raylib cheatsheet, WindowShouldClose, IsKeyPressed and GetTime; libcurl documentation, curl_global_init.

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

The anonymous_id is a UUID version 4 in mana_id.txt, created at the first consent. The queue is mana_queue.txt, up to 1,000 events, rewritten on every Track() call. Paths are relative to the working directory, and raylib has no user data folder function, so a game installed under Program Files or in a macOS app bundle should write to the user data folder of the operating system.

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(0) deletes both files. Whether your game needs consent is a decision for you and your legal advisers.

Sources: raylib cheatsheet, file functions; libcurl documentation; Manalens app events documentation.

## What changes for web, desktop and mobile builds?

raylib builds for Windows, macOS, Linux, Android, Raspberry Pi and the web through Emscripten.

- Desktop: libcurl sends no Origin header, so CORS does not apply and the collector accepts the request with the Publishable key alone.
- Web: use emscripten_fetch() and link with -sFETCH. Set attr.requestMethod to POST, attr.requestHeaders to { "Content-Type", "application/json", "x-publishable-key", MANALENS_KEY, 0 } (the list must end with a null pointer), and attr.requestData to a heap copy of the body. Read fetch->status in onsuccess and onerror, then call emscripten_fetch_close().
- Web CORS: the 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.
- Web files: the default Emscripten file system is in memory and is lost on reload. Mount IDBFS and call FS.syncfs() to keep the queue and the ID.
- Web main loop: the raylib wiki says to avoid the blocking while loop on the web or to compile with ASYNCIFY, because async callbacks run only when control returns to the browser.
- Android: your manifest must declare the INTERNET permission, and libcurl must be built with TLS for Android. Use an https:// endpoint.

Sources: Emscripten documentation, Fetch API and File System API; raylib wiki, Working for Web (HTML5); Manalens app events documentation.

## What are the raylib gotchas?

Most of these come from libcurl and Emscripten, not from raylib.

- libcurl writes the response body to stdout when you set no write callback. Set CURLOPT_WRITEFUNCTION to a function that discards it.
- CURLOPT_POSTFIELDS sends application/x-www-form-urlencoded unless you set Content-Type in CURLOPT_HTTPHEADER. libcurl does not copy the body or the header list, so keep both alive until curl_easy_perform() returns.
- InitWindow() seeds GetRandomValue() with time(NULL). Without a re-seed, players who start in the same second share the same IDs.
- emscripten_fetch() needs the request body to stay valid for the whole request. Do not pass a pointer to memory on the stack; free the copy in both callbacks.
- Web saves vanish on reload unless you mount IDBFS and sync it.

Sources: libcurl documentation, CURLOPT_WRITEDATA, CURLOPT_POSTFIELDS and CURLOPT_HTTPHEADER; raylib source, rcore.c; Emscripten documentation, Fetch API and File System API.

## How do I check that Raylib events arrive?

Send one batch from a development build and read the response status. Print status after curl_easy_getinfo() while you test: 200 means the batch was accepted.

1. Create a test project in Manalens and copy its Publishable key.
2. Build the desktop target with -lcurl and run it from a terminal, then press Y to give consent.
3. Send game_open and session_start from the Raylib 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 libcurl sender to your raylib game, 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 raylib have HTTP functions?

No. raylib covers windows, input, graphics, audio and files, and has no networking. On desktop, send events with libcurl: CURLOPT_HTTPHEADER for the two headers, CURLOPT_POSTFIELDS for the JSON and CURLINFO_RESPONSE_CODE for the status. In a web build, use emscripten_fetch() from Emscripten instead.

### Why do two raylib players get the same ID?

Because raylib 6.2 seeds its random generator with time(NULL) in InitWindow(), in whole seconds. Two players who start in the same second then get the same sequence. Re-seed with SetRandomSeed() and more entropy right after InitWindow(), or read random bytes from the operating system.

### Does the libcurl code work in a raylib web build?

No. libcurl does not work in the browser. Use emscripten_fetch() and link with -sFETCH, with a header list that ends in a null pointer. The browser then sends a CORS preflight, which the collector answers for your project domain, its subdomains and Allowed origins such as *.itch.zone.

### Will sending events slow down my raylib game?

It can. curl_easy_perform() returns only when the request ends, so a slow network stalls the frame. The sample uses a 10 second timeout and flushes every 10 seconds, which is fine for a test. In a shipped game, run Flush() on a worker thread or use the libcurl multi interface.

## Sources

- [raylib cheatsheet (read 18 November 2026)](https://www.raylib.com/cheatsheet/cheatsheet.html)
- [raylib wiki: Working for Web (HTML5) (read 18 November 2026)](https://github.com/raysan5/raylib/wiki/Working-for-Web-(HTML5))
- [libcurl documentation: CURLOPT_HTTPHEADER (read 18 November 2026)](https://curl.se/libcurl/c/CURLOPT_HTTPHEADER.html)
- [libcurl documentation: CURLOPT_POSTFIELDS (read 18 November 2026)](https://curl.se/libcurl/c/CURLOPT_POSTFIELDS.html)
- [libcurl documentation: CURLINFO_RESPONSE_CODE (read 18 November 2026)](https://curl.se/libcurl/c/CURLINFO_RESPONSE_CODE.html)
- [libcurl documentation: CURLOPT_WRITEDATA (read 18 November 2026)](https://curl.se/libcurl/c/CURLOPT_WRITEDATA.html)
- [Emscripten documentation: Fetch API (read 18 November 2026)](https://emscripten.org/docs/api_reference/fetch.html)
- [Emscripten documentation: File System API (read 18 November 2026)](https://emscripten.org/docs/api_reference/Filesystem-API.html)

## 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 Bevy game](https://manalens.dev/blog/bevy-analytics)
- [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)
- [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 Stride game](https://manalens.dev/blog/stride-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)
