Which route fits a Phaser game?
Plain HTTP from the game code. Phaser is a JavaScript framework that runs in a browser, so the browser fetch() is your HTTP client. The Phaser Loader only loads assets; it has no POST call for your own data.
Send app events: channel app, context.app with platform web and engine other. This works on itch.io, because every project allows *.itch.zone by default. If the game runs only on your own domain, you can use the web SDK instead, but you still send the game lifecycle events yourself.
The code below is a small tracker class. It is a starting point that you own, not an SDK. It keeps one player ID, a queue in localStorage, a consent flag and a retry timer.
- Install the web SDK on your game website or browser game →
- Best analytics tools for three.js games in 2026 →
Sources: Phaser documentation, Game and Core Events; MDN, fetch(); Manalens app events documentation.
What must every Phaser 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 Phaser?
Create one tracker for the whole game, next to new Phaser.Game(). fetch() returns a Promise that rejects only on a network or CORS failure. A 4xx or 5xx response resolves normally, so the code reads response.status to decide what to do with the batch.
The UUID helper uses crypto.getRandomValues() and sets the version 4 and variant bits. crypto.randomUUID() also returns a version 4 UUID, but MDN lists it for secure contexts (HTTPS) only.
JavaScript (Phaser 3 or 4)
const MANALENS_URL = 'https://YOUR_COLLECTOR_ENDPOINT/v0/events';
const MANALENS_KEY = 'YOUR_PUBLISHABLE_KEY';
const WEEK_MS = 7 * 24 * 3600 * 1000;
const store = (fn, fallback = null) => { try { return fn(window.localStorage); } catch { return fallback; } };
function uuid4() {
const b = crypto.getRandomValues(new Uint8Array(16));
b[6] = (b[6] & 0x0f) | 0x40; // version 4
b[8] = (b[8] & 0x3f) | 0x80; // variant
const h = Array.from(b, x => x.toString(16).padStart(2, '0')).join('');
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
}
class Analytics {
constructor(game) {
this.queue = JSON.parse(store(s => s.getItem('mana_queue')) || '[]');
this.backoff = 2000; this.retryAt = 0; this.sending = false;
game.events.on(Phaser.Core.Events.HIDDEN, () => this.flush());
}
get consent() { return store(s => s.getItem('mana_consent')) === 'true'; }
setConsent(on) {
store(s => s.setItem('mana_consent', String(on)));
if (!on) { this.queue = []; store(s => { s.removeItem('mana_anon_id'); s.removeItem('mana_queue'); }); }
}
anonId() {
let id = store(s => s.getItem('mana_anon_id'));
if (!id) { id = uuid4(); store(s => s.setItem('mana_anon_id', id)); }
return id;
}
track(event, properties = {}) {
if (!this.consent) return;
this.queue.push({
type: 'track', event, channel: 'app', version: '0.1.0',
message_id: uuid4(), anonymous_id: this.anonId(), session_id: this.session,
original_timestamp: new Date().toISOString(),
context: { app: { platform: 'web', storefront: 'itch', app_version: '1.4.0', build: '571', engine: 'other' },
locale: navigator.language || 'en', library_name: 'my-game', library_version: '1.4.0' },
properties,
});
this.save();
}
save() { store(s => s.setItem('mana_queue', JSON.stringify(this.queue.slice(-1000)))); }
async flush() {
if (!this.consent || this.sending || !this.queue.length || Date.now() < this.retryAt) return;
this.queue = this.queue.filter(e => Date.now() - Date.parse(e.original_timestamp) < WEEK_MS);
const batch = this.queue.slice(0, 50);
if (!batch.length) return this.save();
this.sending = true;
let retry = false;
try {
const res = await fetch(MANALENS_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-publishable-key': MANALENS_KEY },
body: JSON.stringify({ events: batch }),
});
retry = res.status >= 500 || res.status === 408 || res.status === 429;
} catch { retry = true; } // network error or CORS refusal
this.sending = false;
if (retry) { this.retryAt = Date.now() + this.backoff; this.backoff = Math.min(this.backoff * 2, 300000); return; }
this.queue.splice(0, batch.length); this.backoff = 2000; this.save();
if (this.queue.length) this.flush();
}
}Sources: MDN, fetch() and Crypto.getRandomValues(); Phaser documentation, Core Events.
How do I start a session and track game events?
Send game_open and session_start once consent is known, then flush on a timer from a scene. this.time.addEvent() takes a delay, loop and callback. The scene clock stops while the game is paused, which is why the tracker also flushes on HIDDEN.
Use the event conventions, such as level_start, level_complete, level_fail and resource, so the Game KPIs board reads your events without extra setup.
JavaScript
const game = new Phaser.Game(config);
const manalens = new Analytics(game);
function startAnalytics() {
if (!manalens.consent) return;
const firstAt = store(s => s.getItem('mana_first_open_at'));
const now = new Date().toISOString();
if (!firstAt) store(s => s.setItem('mana_first_open_at', now));
manalens.session = uuid4();
manalens.track('game_open', { is_first_open: !firstAt, first_open_at: firstAt || now });
manalens.track('session_start');
manalens.flush();
}
startAnalytics();
// Your consent screen:
// yesButton.on('pointerup', () => { manalens.setConsent(true); startAnalytics(); });
// In a Scene's create():
this.time.addEvent({ delay: 15000, loop: true, callback: () => manalens.flush() });
manalens.track('level_complete', { level: 3, attempt: 1, score: 1200 });Sources: Phaser documentation, Time.Clock and TimerEventConfig; Manalens app events documentation.
How do the player ID, the offline queue and consent work?
The anonymous_id is a UUID in localStorage under mana_anon_id. It is created on the first tracked event after consent, and the same ID goes on every later event. The queue is a JSON array under mana_queue, capped at 1,000 events, so a player who plays offline sends the events at the next flush or the next launch.
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. The flush also drops events older than 7 days, because one old event refuses the whole batch with 400.
Consent is a flag in mana_consent. Until it is "true", track() does nothing and no ID is written. setConsent(false) deletes the ID and the queue. Whether your game needs consent is a decision for you and your legal advisers.
localStorage throws a SecurityError in some contexts, for example when the player blocks site data. The store() wrapper catches it, so the game keeps running without analytics.
Sources: MDN, Window.localStorage; Manalens app events documentation.
What changes for web, desktop and mobile builds?
Phaser targets the browser. Desktop and mobile builds come from a wrapper such as Electron, NW.js, Tauri, Capacitor or Cordova. Those are separate projects, so check their docs for storage and network rules.
- CORS: the x-publishable-key header and the application/json content type are not on the CORS safelist, so the browser sends an OPTIONS preflight before each POST. The collector answers it for your project domain, its subdomains and the hosts in Allowed origins.
- itch.io: the game runs in an iframe served from an itch.zone host. *.itch.zone is allowed by default, so no setup is needed. Calls from itch.io to another domain must use HTTPS.
- Other portals: add the host that serves the game files (not the portal page) under Project settings, Allowed origins. A host that is not on the list gets 403.
- Mobile wrappers: the WebView page has its own origin. Find it in the wrapper docs and add it to Allowed origins. Use an https:// endpoint, because Android and iOS block cleartext HTTP by default.
- Electron: serve the renderer from an https:// URL on your project domain, or send events from the main process. The app events docs explain both options.
- navigator.sendBeacon() cannot set custom headers, so it cannot send the x-publishable-key header. Use fetch().
Sources: Phaser documentation, Installing; MDN, Preflight request; itch.io documentation, HTML5 games; Manalens app events documentation.
What are the Phaser gotchas?
These problems show up after the first real players, not in a local test.
- Do not use Phaser.Math.RND.uuid() for IDs. It uses the game random generator, and if you set a seed in the game config for repeatable gameplay, every player gets the same sequence of IDs.
- The HIDDEN event pauses the game loop, so this.time.addEvent() timers stop while the tab is in the background. Flush in the HIDDEN handler itself. MDN calls the change to hidden the last event that the page can reliably observe.
- fetch() does not reject on 4xx or 5xx. A plain .catch() misses server errors, so read response.status.
- Browsers partition storage by the top-level site. A player who plays on itch.io and then on your own site has two anonymous IDs. Use identify() with your own account ID if you need to join them.
- A blocked preflight looks like a network error in JavaScript. If the queue never empties on a new portal, open the browser console: a CORS error means the host is missing from Allowed origins.
Sources: Phaser documentation, Game, Core Events and RandomDataGenerator; MDN, fetch(), State partitioning and visibilitychange.
How do I check that Phaser events arrive?
Send one batch from a development build and read the response status. In the browser network panel, the OPTIONS preflight should succeed before the POST. A 403 means the page host is not allowed.
- Create a test project in Manalens and copy its Publishable key.
- Run the game with a local server on a host in Allowed origins (add localhost for the test), or upload a draft to itch.io.
- Send game_open and session_start from the Phaser 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 the tracker to your Phaser game, send game_open and session_start, and open the Game KPIs board to see D1 retention and level fail rates for each build.
Sources: Manalens product documentation.
Frequently asked questions
Does Phaser have built-in analytics?
No. Phaser has no analytics module and no HTTP POST helper, and its Loader only loads assets. Send events with the browser fetch() to /v0/events with your Publishable key. Keep a player ID and an event queue in localStorage, and flush on a timer and on the Phaser HIDDEN event.
Can I send events from a Phaser game on itch.io?
Yes. itch.io serves HTML5 games from itch.zone hosts, and every Manalens project allows *.itch.zone by default. The browser sends a CORS preflight because of the x-publishable-key header, and the collector answers it for allowed hosts. Other portals need their file host added under Allowed origins.
Why does every player get the same anonymous ID?
Most likely the ID comes from Phaser.Math.RND.uuid() and your game config sets a seed. The seeded generator then gives every player the same sequence. Create the ID with crypto.getRandomValues() and the version 4 bits, as in the code sample, and save it in localStorage.
What happens when the player closes the tab?
The Phaser HIDDEN event fires first, and the tracker flushes the queue then. If the request does not finish, the events stay in localStorage and go out at the next launch. The collector accepts events up to 7 days old, and each message_id counts once.
Sources and implementation
- Phaser documentation: Core Events (HIDDEN, VISIBLE) (read 18 November 2026) ↗
- Phaser documentation: Game class (read 18 November 2026) ↗
- Phaser documentation: Time.Clock (read 18 November 2026) ↗
- MDN Web Docs: Window.fetch() (read 18 November 2026) ↗
- MDN Web Docs: Crypto.getRandomValues() (read 18 November 2026) ↗
- MDN Web Docs: Preflight request (read 18 November 2026) ↗
- MDN Web Docs: State partitioning (read 18 November 2026) ↗
- itch.io documentation: Uploading HTML5 games (read 18 November 2026) ↗