# How to add analytics to a Defold game

> Send Defold game events with http.request: a Lua module with a saved player ID, a sys.save queue with retries, consent, and HTML5 and mobile notes.

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

Defold has a built-in HTTP client, so a small Lua module can post events to /v0/events with http.request(), up to 50 per request. The Defold reference says the callback gets response.status, and sys.save() writes a Lua table to the save folder, or to IndexedDB on HTML5. Always pass a timeout of 10 seconds.

## Key points

- Always pass a timeout of 10 to Defold http.request(), because an unset timeout is 0 and one stuck request blocks every later flush.
- Wrap Defold sys.load() in pcall(), because one corrupt save file raises a Lua error that stops the game at start.
- Cap the Defold queue at 1,000 events, because sys.save() has a limit of 512 KB per file.

## Which route fits a Defold game?

The built-in http.request(url, method, callback, headers, post_data, options). It is async, works on every Defold target, and gives the callback a response table with status, response, headers and error. json.encode() turns a Lua table into the JSON body.

Put the code in a Lua module, main/analytics.lua, and call it from the script of a game object that lives for the whole game. Any script can then require the module and call track().

Sources: Defold API reference, http, json and sys; Defold manual, HTTP requests.

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

The module keeps two save files from sys.get_save_file(): mana_state for the consent flag, the ID and the first open time, and mana_queue for the queue as one JSON string. sys.load() raises an error on a corrupt file, so the code wraps it in pcall().

os.date() with a format that starts with ! gives UTC, so now_iso() returns the Z form. The UUID uses math.random() after math.randomseed(); the reference has no note that the generator is seeded for you.

``` Lua (main/analytics.lua)
-- main/analytics.lua
local M = {}
local URL = "https://YOUR_COLLECTOR_ENDPOINT/v0/events"
local KEY = "YOUR_PUBLISHABLE_KEY"
local WEEK = 7 * 24 * 3600
local STATE = sys.get_save_file("my_game", "mana_state")
local QUEUE = sys.get_save_file("my_game", "mana_queue")
local PLATFORMS = { Windows = "windows", Darwin = "macos", Linux = "linux",
  HTML5 = "web", Android = "android", ["iPhone OS"] = "ios" }
local st, queue, sending, retry_at, backoff, session_id = {}, {}, false, 0, 2, nil

local function uuid4()
  local b = {}
  for i = 1, 16 do b[i] = math.random(0, 255) end
  b[7] = b[7] % 16 + 64   -- version 4
  b[9] = b[9] % 64 + 128  -- variant
  local s = string.format(string.rep("%02x", 16), unpack(b))
  return s:sub(1, 8) .. "-" .. s:sub(9, 12) .. "-" .. s:sub(13, 16) .. "-" .. s:sub(17, 20) .. "-" .. s:sub(21)
end

local function now_iso(t) return os.date("!%Y-%m-%dT%H:%M:%S.000Z", t) end
local function save_queue() sys.save(QUEUE, { json = json.encode(queue) }) end

function M.track(name, props)
  if not st.consent then return end
  local info = sys.get_sys_info()
  queue[#queue + 1] = { type = "track", event = name, channel = "app", version = "0.1.0",
    message_id = uuid4(), anonymous_id = st.anonymous_id, session_id = session_id,
    original_timestamp = now_iso(),
    context = { app = { platform = PLATFORMS[info.system_name] or "other", storefront = "steam",
      app_version = "1.4.0", build = "571", engine = "other" },
      locale = info.language, library_name = "my-game", library_version = "1.4.0" },
    properties = props or {} }
  if #queue > 1000 and not sending then table.remove(queue, 1) end
  save_queue()
end

local function start()
  local first = st.first_open_at == nil
  if first then st.first_open_at = now_iso(); sys.save(STATE, st) end
  M.track("game_open", { is_first_open = first, first_open_at = st.first_open_at })
  M.track("session_start", {})
end

function M.set_consent(on)
  if on and not st.consent then
    st.consent, st.anonymous_id = true, st.anonymous_id or uuid4()
    sys.save(STATE, st)
    start()
  elseif not on then
    st, queue = { consent = false }, {}
    sys.save(STATE, st)
    save_queue()
  end
end

function M.flush()
  if sending or not st.consent or os.time() < retry_at then return end
  local cutoff = now_iso(os.time() - WEEK)
  while queue[1] and queue[1].original_timestamp < cutoff do table.remove(queue, 1) end
  if #queue == 0 then return end
  local n, batch = math.min(50, #queue), {}
  for i = 1, n do batch[i] = queue[i] end
  sending = true
  local headers = { ["Content-Type"] = "application/json", ["x-publishable-key"] = KEY }
  http.request(URL, "POST", function(self, id, res)
    sending = false
    local s = res.status or 0
    if (s >= 200 and s < 300) or (s >= 400 and s < 500 and s ~= 408 and s ~= 429) then
      for _ = 1, math.min(n, #queue) do table.remove(queue, 1) end
      save_queue()
      backoff = 2
    else
      retry_at = os.time() + backoff
      backoff = math.min(backoff * 2, 300)
    end
  end, headers, json.encode({ events = batch }), { timeout = 10 })
end

function M.init()
  math.randomseed(os.time() + math.floor(os.clock() * 1000000))
  local ok, s = pcall(sys.load, STATE)
  st = ok and s or {}
  local okq, q = pcall(sys.load, QUEUE)
  local okd, list = pcall(json.decode, okq and q.json or "[]")
  queue = okd and list or {}
  session_id = uuid4()
  if st.consent then start() end
end

return M
```

Sources: Defold API reference, http, sys, json, os and math; Defold manual, File access.

## How do I start the module and flush the queue?

Call init() once from the script of a game object in your bootstrap collection. timer.delay() flushes every 10 seconds. window.set_listener() flushes when the game loses focus or is minimized, which is the last safe moment on mobile and on the web. Only one window listener can be set, so merge this with any listener you already have.

Track gameplay from any script with manalens.track("level_complete", { level = 3, score = 1200 }). Use the event conventions so the Game KPIs board reads them.

``` Lua (main/main.script)
-- main/main.script
local manalens = require "main.analytics"

function init(self)
  manalens.init()
  timer.delay(10, true, function() manalens.flush() end)
  window.set_listener(function(self, event, data)
    if event == window.WINDOW_EVENT_FOCUS_LOST or event == window.WINDOW_EVENT_ICONIFIED then
      manalens.flush()
    end
  end)
end

-- Consent screen (any script or GUI script):
-- manalens.set_consent(true)
-- Gameplay:
-- manalens.track("level_complete", { level = 3, attempt = 1, score = 1200 })
```

Sources: Defold API reference, timer and window; Defold manual, Application lifecycle; Manalens app events documentation.

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

The anonymous_id is a UUID version 4 in mana_state, created when the player gives consent. The queue in mana_queue is capped at 1,000 events and saved on every track() call. A player who plays offline sends it 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.

Until consent is true, track() does nothing and no ID is written. set_consent(false) clears the ID and the queue. Whether your game needs consent is a decision for you and your legal advisers.

Sources: Defold API reference, sys; Manalens app events documentation.

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

The same module runs on Windows, macOS, Linux, Android, iOS and HTML5.

- Desktop and mobile: a native build sends no Origin header, so the collector accepts it with the Publishable key alone.
- HTML5: the Defold manual says cross-origin requests need compatible CORS headers. The x-publishable-key header causes a CORS preflight, which the collector answers for your project domain, its subdomains and Allowed origins. *.itch.zone is allowed by default.
- HTML5 options: the ignore_cache and chunked_transfer request options are not available on HTML5. The timeout option works.
- HTML5 storage: sys.save() writes to IndexedDB, and the manual warns of a short delay before a write is stored. A save just before the tab closes can be lost, so the queue is saved on every event, not at quit.
- Android: the default Defold manifest already asks for network access. Use an https:// endpoint on Android and iOS, because both block cleartext HTTP by default.

Sources: Defold manual, HTML5, Android and HTTP requests; Defold API reference, http and sys; Manalens app events documentation.

## What are the Defold gotchas?

These come from the Defold reference and manuals.

- Without a timeout option, and with network.http_timeout unset in the project settings, the timeout is 0, which waits forever. One stuck request then blocks every later flush. Always pass { timeout = 10 }.
- sys.load() raises a Lua error on a corrupt file. Without pcall(), one bad write stops the game at start.
- sys.save() has a limit of 512 KB per file. Cap the queue, as the module does at 1,000 events.
- Bodies over 16,384 bytes are sent with chunked transfer encoding on native builds. A batch of 50 events can pass that size, so test a full batch once.
- The callback id is an internal message ID that the reference says not to use. Keep your own state, such as the sending flag, to match a reply to its batch.

Sources: Defold API reference, http and sys; Defold manual, Project settings, File access, HTML5 and HTTP requests.

## How do I check that Defold events arrive?

Send one batch from a development build and read the response status. Add print(res.status) in the http.request callback while you test: it should print 200.

1. Create a test project in Manalens and copy its Publishable key.
2. Build and run from the Defold editor (Project, Build) with a test Publishable key, then build HTML5 once.
3. Send game_open and session_start from the Defold 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 Lua module, ask for consent, and use the Game KPIs board to see retention and level fail rates for each build and platform.

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

Sources: Manalens product documentation.

## Frequently asked questions

### Does Defold have built-in HTTP?

Yes. http.request() sends a request with custom headers and a body, and calls your function with response.status, the body and the headers. It is async and works on every Defold target, including HTML5. Always pass a timeout, because the default can wait forever when the project setting is unset.

### Where does Defold save the player ID?

In a file from sys.get_save_file(), written with sys.save() and read with sys.load(). On desktop and mobile it is in a folder under the user home directory. On HTML5 it is stored in IndexedDB. Wrap sys.load() in pcall(), because it raises an error on a corrupt file.

### Does the Defold code work on HTML5 and itch.io?

Yes. http.request() works on HTML5, and the browser sends a CORS preflight because of the x-publishable-key header. The collector answers it for your project domain and Allowed origins, and *.itch.zone is allowed by default. Save the queue on every event, because IndexedDB writes have a short delay.

## Sources

- [Defold API reference: http (read 18 November 2026)](https://defold.com/ref/http/)
- [Defold API reference: sys (read 18 November 2026)](https://defold.com/ref/sys/)
- [Defold API reference: json (read 18 November 2026)](https://defold.com/ref/json/)
- [Defold API reference: window (read 18 November 2026)](https://defold.com/ref/window/)
- [Defold API reference: timer (read 18 November 2026)](https://defold.com/ref/timer/)
- [Defold manual: HTTP requests (read 18 November 2026)](https://defold.com/manuals/http-requests/)
- [Defold manual: File access (read 18 November 2026)](https://defold.com/manuals/file-access/)
- [Defold manual: HTML5 (read 18 November 2026)](https://defold.com/manuals/html5/)
- [Defold manual: Project settings (read 18 November 2026)](https://defold.com/manuals/project-settings/)

## 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 LÖVE (Love2D) game](https://manalens.dev/blog/love2d-analytics)
- [What events to track first in your game](https://manalens.dev/blog/game-tracking-plan-first-events)
- [Track an itch.io game](https://manalens.dev/integrations/itch-io)
- [Player analytics guides](https://manalens.dev/blog/topic/player-analytics)
- [Best game telemetry tools in 2026](https://manalens.dev/blog/best-game-telemetry-tools)
- [Build vs buy a game analytics pipeline](https://manalens.dev/blog/build-vs-buy-game-analytics-pipeline)
- [How to add analytics to a HaxeFlixel game](https://manalens.dev/blog/haxeflixel-analytics)
- [How to add analytics to a GameMaker game](https://manalens.dev/blog/gamemaker-analytics)
