# Analytics API reference

> Every public function and field of the Analytics module, with parameters, return values, behaviour and an example for each.

This is the complete public API of the `Analytics` module, version `1.0.0`. Require it from server code only:

```luau
local Analytics = require(game.ServerScriptService.Analytics)
```

Unless a function says otherwise:

- it returns nothing and **never yields**: it validates its arguments and adds an event to the queue;
- an invalid argument drops the call, usually with a warning printed once per server per distinct problem (prefixed `[Bloxlytics]`);
- before `Start`, after a failed `Start`, or in Studio without `TrackInStudio`, it does nothing.

Every function is called with a colon (`Analytics:TrackEvent(…)`).

| Function | Section |
| --- | --- |
| `Start`, `Init`, `Flush`, `GetStats` | [Lifecycle](#lifecycle) |
| `SetServerTag` | [Server tags](#server-tags) |
| `TrackEvent`, `TrackFunnel`, `TrackProgression` | [Events](#events) |
| `TrackCurrencyEarned`, `TrackCurrencySpent`, `TrackBalance`, `TrackCurrencyTransfer` | [Economy](#economy) |
| `WrapProcessReceipt`, `SetProductNames` | [Purchases](#purchases) |
| `SetPlayerProperty`, `SetPlayerProperties`, `SetPlayerRole` | [Player properties](#player-properties) |
| `GetVariant` | [Experiments](#experiments) |
| `Version`, `ServerKey` | [Fields](#fields) |

## Lifecycle

### Start

```luau
Analytics:Start(config: Config): boolean
```

Starts analytics and, when `config.Cmdr` is set, the [Cmdr bridge](https://docs.bloxlytics.app/sdk/cmdr-bridge). Call it once, from a server Script, as early as possible.

- `config` (table, body, required): The configuration. `WriteKey` and `ApiUrl` are required; every field is listed on [configuration](https://docs.bloxlytics.app/sdk/configuration#all-fields).

- `returns` (boolean): `true` when analytics started (including in Studio, where it then stays idle without `TrackInStudio`). `false` when the configuration was rejected, `Start` or `Init` was already called, or it isn't running on the server. Bridge problems never change the result.

Behaviour:

1. Runs [`Init`](#init) with the same table.
2. If `config.Cmdr` is set, finds a ModuleScript named `CmdrBridge` inside the `Analytics` module or next to it, and calls `CmdrBridge:Init` with `Cmdr`, `BridgeKey`, `ApiUrl`, `ProjectID`, `AllowedGroups`, `AllowKick`, `OnWarn`, `OnAnnounce`, `AllowSystemCommands`, `Debug`, `EnableInStudio = (EnableBridgeInStudio ~= false)` and `Analytics` itself. This happens whether or not analytics started, so the bridge can run even when analytics is off.
3. In Studio, prints this session's server key: `[Bloxlytics] Studio session. Target this server from the website with server "studio-…".`

Bridge warnings, each of which leaves analytics unaffected:

- `Cmdr was passed but the CmdrBridge module wasn't found next to or inside Analytics; remote commands are off`
- `Cmdr was passed without BridgeKey; remote commands are off`
- `Cmdr bridge didn't start: <error>`, plus the bridge's own `[Bloxlytics bridge] Not started: …` warnings.

```luau
local HttpService = game:GetService("HttpService")
local Analytics = require(game.ServerScriptService.Analytics)

local started = Analytics:Start({
	WriteKey = HttpService:GetSecret("bloxlytics_write_key"),
	ApiUrl = "https://api.bloxlytics.app",
})
if not started then
	-- The warning in the output says why. The game carries on either way.
end
```

### Init

```luau
Analytics:Init(config: Config): boolean
```

Starts analytics only. Bridge fields in `config` are ignored. Prefer [`Start`](#start); use `Init` if you start `CmdrBridge` yourself.

- `config` (table, body, required): The same table as `Start`.

- `returns` (boolean): `true` when the configuration is usable, `false` otherwise.

Behaviour:

- Refuses to run on a client (`The SDK only runs on the server; require it from a server Script`) and refuses a second call (`Init/Start called twice; ignoring the second call`).
- Checks the configuration (see [validation order](https://docs.bloxlytics.app/sdk/configuration#validation-order)). On a problem: `Not started: <problem>. Your game keeps running without analytics.`
- Removes trailing slashes from `config.ApiUrl` and replaces `config.ProjectID` with the resolved Universe ID, in the table you passed.
- In Studio without `TrackInStudio`, returns `true` here without starting anything.
- Otherwise: applies `FlushInterval` (clamped 2–60) and `MaxBatchSize` (clamped 10–500); on a new thread fetches remote configuration, queues `$server_start` and starts sessions for players already in the server; connects `PlayerAdded` and `PlayerRemoving` (unless `AutoTrackSessions = false`), `PromptGamePassPurchaseFinished` (unless `AutoTrackGamePasses = false`) and `PromptProductPurchaseFinished`; starts the once-a-second loop for heartbeats, configuration refreshes and flushes; and binds the shutdown flush with `game:BindToClose`.

```luau
local Analytics = require(game.ServerScriptService.Analytics)

Analytics:Init({
	WriteKey = "bxw_…",
	ApiUrl = "https://api.bloxlytics.app",
})
```

### Flush

```luau
Analytics:Flush()
```

Sends queued events now instead of waiting for the next flush interval. **Yields** while requests are in flight.

It sends batches until the queue is empty or a send fails. It returns immediately if a flush is already running, the SDK isn't enabled, or the SDK is backing off after a failure. You rarely need it: the SDK flushes every few seconds and on shutdown. It is useful just before you teleport every player out of a server. See [delivery](https://docs.bloxlytics.app/sdk/delivery).

```luau
Analytics:TrackEvent("RoundEnded", { Map = "Forest" })
task.spawn(function()
	Analytics:Flush()
end)
```

### GetStats

```luau
Analytics:GetStats(): { queued: number, dropped: number, enabled: boolean, backoff: number }
```

Returns a snapshot of the SDK's state on this server. Works at any time, including before `Start`.

- `queued` (number): Events waiting to be sent.

- `dropped` (number): Events dropped since start-up because the queue reached 5,000.

- `enabled` (boolean): Whether the SDK is queuing and sending events.

- `backoff` (number): The current retry delay in seconds (2 to 60), or `0` when the last send succeeded.

```luau
local stats = Analytics:GetStats()
if stats.dropped > 0 then
	warn(`Bloxlytics dropped {stats.dropped} events; {stats.queued} still queued`)
end
```

## Server tags

### SetServerTag

```luau
Analytics:SetServerTag(name: string, value: any?)
```

Sets a short fact about this server, such as the map, mode or region. Tags appear on the server's card in Bloxlytics and can be searched in server pickers. **Works before `Start`**, so you can tag a server before its first event.

- `name` (string, body, required): Starts with a letter; then letters, digits, spaces and `_` `.` `-`; at most 32 characters. Otherwise dropped with `SetServerTag: invalid tag name <name> (letters, digits, space . _ -, max 32)`.

- `value` (any, body): Converted with `tostring` and cut to 64 characters. `nil` removes the tag.

A server can have at most 16 tags. Adding a 17th is dropped with `SetServerTag: at most 16 tags per server`; changing an existing tag is always allowed. Tags are sent with `$server_start`, every heartbeat (so changes appear within about 30 seconds) and every Cmdr bridge poll.

```luau
Analytics:SetServerTag("map", "Forest")
Analytics:SetServerTag("round", 3) -- sent as "3"
Analytics:SetServerTag("round", nil) -- removed
```

## Events

### TrackEvent

```luau
Analytics:TrackEvent(player: Player?, name: string, properties: { [string]: any }?)
Analytics:TrackEvent(name: string, properties: { [string]: any }?, player: Player?)
```

Tracks a custom event. If the first argument is a `Player`, the arguments are `(player, name, properties)`; otherwise `(name, properties, player)`.

- `player` (Player, body): The player the event is about. Leave it out for server-level events. Anything other than a `Player` drops the call: `TrackEvent(<name>): player must be a Player`.

- `name` (string, body, required): Starts with a letter; then letters, digits, spaces and `_` `.` `:` `-`; at most 64 characters. Otherwise: `TrackEvent: invalid event name <name>`.

- `properties` (table, body): Up to 32 properties. Keys start with a letter or `_`, then letters, digits, spaces and `_` `.` `-`, at most 40 characters. Values: strings (cut to 256 characters), finite numbers, booleans; `EnumItem` and `Instance` values are converted with `tostring`. Other values are dropped with a warning. Full rules on [custom events](https://docs.bloxlytics.app/sdk/custom-events#properties).

Dropped without a warning when **Custom events** is off or the name is in **Blocked events** in the dashboard.

```luau
Analytics:TrackEvent(player, "PetHatched", { PetName = "Dragon", Rarity = "Legendary", Island = 3 })
Analytics:TrackEvent("BossSpawned", { Boss = "Kraken" })
```

### TrackFunnel

```luau
Analytics:TrackFunnel(player: Player, funnel: string, step: string, index: number?)
Analytics:TrackFunnel(funnel: string, step: string, player: Player, index: number?)
```

Records a funnel step as a `$funnel` event.

- `player` (Player, body, required): Funnels are per player. Without one: `TrackFunnel(<funnel>): pass the player so the step can be attributed`.

- `funnel` (string, body, required): Non-empty; cut to 64 characters.

- `step` (string, body, required): Non-empty; cut to 64 characters. An empty funnel or step: `TrackFunnel: funnel and step must be non-empty strings`.

- `index` (number, body): Optional step number, rounded down, that orders steps in the funnel builder. Must not be negative.

```luau
Analytics:TrackFunnel(player, "Tutorial", "Started", 0)
Analytics:TrackFunnel("Tutorial", "Completed", player, 3)
```

### TrackProgression

```luau
Analytics:TrackProgression(player: Player, status: "start" | "complete" | "fail", path: string, score: number?)
```

Records a `$progression` event.

- `player` (Player, body, required): The player.

- `status` (string, body, required): `"start"`, `"complete"` or `"fail"`.

- `path` (string, body, required): What was attempted, such as `"World1:Level3"`. Cut to 128 characters.

- `score` (number, body): Optional, finite.

Invalid arguments: `TrackProgression(player, 'start'|'complete'|'fail', path, score?)`.

```luau
Analytics:TrackProgression(player, "complete", "World1:Level3", 870)
```

## Economy

All four functions send economy events, are dropped when **Economy** is off in the dashboard, and require `currency` to be a non-empty string (`Economy: currency must be a non-empty string`). If the dashboard defines currencies and this one isn't among them (ignoring case), the event is still sent but the SDK warns once: `Currency "<name>" isn't configured in Bloxlytics → SDK settings; events will be rejected`. A missing player or an invalid amount is dropped **without** a warning. See [economy](https://docs.bloxlytics.app/sdk/economy).

### TrackCurrencyEarned

```luau
Analytics:TrackCurrencyEarned(player: Player, currency: string, amount: number, source: string?, item: string?, balance: number?)
```

Records a currency source: a `$economy` event with `flow = "source"`.

- `player` (Player, body, required): The player who received the currency.

- `currency` (string, body, required): Currency key, at most 32 characters.

- `amount` (number, body, required): Greater than 0 and finite.

- `source` (string, body): Category, such as `"Quests"`. At most 64 characters (not shortened by the SDK; longer values are rejected by the API).

- `item` (string, body): What earned it. At most 64 characters.

- `balance` (number, body): The balance after the change. Finite.

```luau
Analytics:TrackCurrencyEarned(player, "Coins", 150, "Quests", nil, newBalance)
```

### TrackCurrencySpent

```luau
Analytics:TrackCurrencySpent(player: Player, currency: string, amount: number, sink: string?, item: string?, balance: number?)
```

Records a currency sink: a `$economy` event with `flow = "sink"`. Parameters are the same as `TrackCurrencyEarned`, with `sink` in place of `source`. `amount` is positive.

```luau
Analytics:TrackCurrencySpent(player, "Coins", 500, "Eggs", "GoldenEgg", newBalance)
```

### TrackBalance

```luau
Analytics:TrackBalance(player: Player, currency: string, balance: number)
```

Records a `$balance` snapshot without a change.

- `player` (Player, body, required): The player.

- `currency` (string, body, required): Currency key.

- `balance` (number, body, required): The current balance. Finite; zero and negative values are allowed.

```luau
Analytics:TrackBalance(player, "Gems", gems)
```

### TrackCurrencyTransfer

```luau
Analytics:TrackCurrencyTransfer(from: Player, to: Player | number, currency: string, amount: number, reason: string?)
```

Records currency moving between players, as a `$economy_transfer` event belonging to `from`.

- `from` (Player, body, required): The sender.

- `to` (Player | number, body, required): The receiver, as a `Player` or a positive user id.

- `currency` (string, body, required): Currency key.

- `amount` (number, body, required): Greater than 0 and finite.

- `reason` (string, body): Such as `"Trade"` or `"Gift"`. At most 64 characters.

```luau
Analytics:TrackCurrencyTransfer(player, otherPlayer, "Coins", 100, "Trade")
```

## Purchases

Purchase tracking is dropped when **Purchases** is off in the dashboard. Game pass prompts and developer product prompt attempts are tracked automatically; see [purchases](https://docs.bloxlytics.app/sdk/purchases).

### WrapProcessReceipt

```luau
Analytics:WrapProcessReceipt(handler: (receipt) -> Enum.ProductPurchaseDecision): (receipt) -> Enum.ProductPurchaseDecision
```

Wraps your `ProcessReceipt` handler so granted developer product purchases are recorded.

- `handler` (function, body, required): Your existing handler. Anything else raises `WrapProcessReceipt expects your ProcessReceipt function`. This is the only SDK function that can raise an error.

- `returns` (function): A function to assign to `MarketplaceService.ProcessReceipt`. It calls your handler, and when the decision is `PurchaseGranted` and the player is in the server, queues a completed `$purchase` with `productId = receipt.ProductId`, `robux = receipt.CurrencySpent` and `receiptId = receipt.PurchaseId`. It returns your handler's decision unchanged. Recording runs inside `pcall`; errors from your handler are not caught.

The first receipt for each product **may yield** while the product's name is looked up with `GetProductInfo`, unless you named it with `SetProductNames`.

```luau
local MarketplaceService = game:GetService("MarketplaceService")

MarketplaceService.ProcessReceipt = Analytics:WrapProcessReceipt(function(receipt)
	-- grant the product here
	return Enum.ProductPurchaseDecision.PurchaseGranted
end)
```

### SetProductNames

```luau
Analytics:SetProductNames(names: { [number]: string })
```

Gives developer products names to use instead of looking them up with `MarketplaceService:GetProductInfo`. Works before `Start`.

- `names` ({ [number]: string }, body, required): Developer product id to name. Adds to or replaces names from earlier calls.

Applies to developer products only, not game passes. A product already looked up on this server keeps its cached name, so call it at start-up. Prompt attempts for a named product carry no `robux` price.

```luau
Analytics:SetProductNames({ [1001] = "500 Gems", [1002] = "2,500 Gems" })
```

## Player properties

Player properties describe a player: level, rebirths, island, VIP, player type, role. Each one is sent as its own `$property` event and shown on the player's profile in [Players](https://docs.bloxlytics.app/analytics/players); they can be used in [segments](https://docs.bloxlytics.app/analytics/segments) and drive [player banners](https://docs.bloxlytics.app/sdk/remote-config#player-banners). They aren't affected by any tracking switch.

### SetPlayerProperty

```luau
Analytics:SetPlayerProperty(player: Player, key: string, value: string | number | boolean)
```

- `player` (Player, body, required): The player.

- `key` (string, body, required): Starts with a letter or `_`; then letters, digits, spaces and `_` `.` `-`; at most 40 characters. An invalid key (or a missing player) is dropped with `SetPlayerProperty: invalid key <key>`.

- `value` (string | number | boolean, body, required): Strings are cut to 256 characters; numbers must be finite. Any other type: `SetPlayerProperty(<key>): value must be a string, number or boolean`.

```luau
Analytics:SetPlayerProperty(player, "Level", 12)
```

### SetPlayerProperties

```luau
Analytics:SetPlayerProperties(player: Player, properties: { [string]: string | number | boolean })
```

Calls `SetPlayerProperty` for each entry, so each property is validated and sent as its own event. There is no 32-property limit here.

- `player` (Player, body, required): The player.

- `properties` (table, body, required): Key to value, with the same rules as `SetPlayerProperty`.

```luau
Analytics:SetPlayerProperties(player, {
	Level = 12,
	Rebirths = 2,
	Island = "Volcano",
	VIP = true,
	PlayerType = "Grinder",
})
```

### SetPlayerRole

```luau
Analytics:SetPlayerRole(player: Player, role: string)
```

Reports a verified in-game role. Same as `SetPlayerProperty(player, "Role", role)`. Combine it with a banner rule such as **Role** equals `Moderator` to show staff in Bloxlytics.

- `player` (Player, body, required): The player.

- `role` (string, body, required): The role, such as `"Moderator"`. Cut to 256 characters.

```luau
if isModerator(player) then
	Analytics:SetPlayerRole(player, "Moderator")
end
```

## Experiments

### GetVariant

```luau
Analytics:GetVariant(player: Player, experimentKey: string): (string?, { [string]: any }?)
```

Returns the player's variant of a running experiment, using the same deterministic assignment as Bloxlytics. Logs a `$experiment_exposure` the first time in each session. Doesn't yield. See [experiments](https://docs.bloxlytics.app/sdk/experiments).

- `player` (Player, body, required): The player. Anything else returns `nil, nil`.

- `experimentKey` (string, body, required): The experiment's key from the dashboard.

- `variant` (string?): The variant key, or `nil` when the experiment isn't running on this server, the player is outside the allocation, or remote configuration hasn't loaded.

- `config` (table?): The variant's config from the dashboard, or `nil` with `variant`.

```luau
local variant, config = Analytics:GetVariant(player, "starting-coins")
if variant and config then
	coins = config.StartingCoins
end
```

## Fields

- `Analytics.Version` (string): The module's version, `"1.0.0"`. Sent with every batch and shown as **SDK version** in the debugger.

- `Analytics.ServerKey` (string): This server's id in Bloxlytics: `game.JobId` in a live server, or `studio-` followed by 8 random hex characters in Studio. Set when the module is first required; the Cmdr bridge uses the same value.

```luau
print("This server in Bloxlytics:", Analytics.ServerKey)
```

## Internal members

The module also has members whose names start with `_`: `_getServerTags`, `_setBridgeActive`, `_trackPrompt` and `_fnv1a`. They exist so the Cmdr bridge and the SDK's own handlers can talk to each other. Don't call them: they skip validation and may change in any version.

## Types

```luau
type Config = {
	ProjectID: (string | number)?,
	WriteKey: any, -- string or Secret
	ApiUrl: string,
	Cmdr: any?,
	BridgeKey: any?, -- string or Secret
	AllowSystemCommands: boolean?,
	AllowedGroups: { string }?,
	AllowKick: boolean?,
	OnWarn: ((Player, string) -> ())?,
	OnAnnounce: ((string) -> ())?,
	EnableBridgeInStudio: boolean?,
	FlushInterval: number?,
	MaxBatchSize: number?,
	TrackInStudio: boolean?,
	AutoTrackSessions: boolean?,
	AutoTrackGamePasses: boolean?,
	Debug: boolean?,
}
```
