Reference

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:

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
SetServerTag Server tags
TrackEvent, TrackFunnel, TrackProgression Events
TrackCurrencyEarned, TrackCurrencySpent, TrackBalance, TrackCurrencyTransfer Economy
WrapProcessReceipt, SetProductNames Purchases
SetPlayerProperty, SetPlayerProperties, SetPlayerRole Player properties
GetVariant Experiments
Version, ServerKey Fields

#Lifecycle

#Start

Analytics:Start(config: Config): boolean

Starts analytics and, when config.Cmdr is set, the Cmdr bridge. Call it once, from a server Script, as early as possible.

configtablebodyrequired

The configuration. WriteKey and ApiUrl are required; every field is listed on configuration.

returnsboolean

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 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.
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

Analytics:Init(config: Config): boolean

Starts analytics only. Bridge fields in config are ignored. Prefer Start; use Init if you start CmdrBridge yourself.

configtablebodyrequired

The same table as Start.

returnsboolean

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). 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.
local Analytics = require(game.ServerScriptService.Analytics)

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

#Flush

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.

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

#GetStats

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.

queuednumber

Events waiting to be sent.

droppednumber

Events dropped since start-up because the queue reached 5,000.

enabledboolean

Whether the SDK is queuing and sending events.

backoffnumber

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

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

#Server tags

#SetServerTag

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.

namestringbodyrequired

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).

valueanybody

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.

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

#Events

#TrackEvent

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).

playerPlayerbody

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.

namestringbodyrequired

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

propertiestablebody

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.

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

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

#TrackFunnel

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.

playerPlayerbodyrequired

Funnels are per player. Without one: TrackFunnel(<funnel>): pass the player so the step can be attributed.

funnelstringbodyrequired

Non-empty; cut to 64 characters.

stepstringbodyrequired

Non-empty; cut to 64 characters. An empty funnel or step: TrackFunnel: funnel and step must be non-empty strings.

indexnumberbody

Optional step number, rounded down, that orders steps in the funnel builder. Must not be negative.

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

#TrackProgression

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

Records a $progression event.

playerPlayerbodyrequired

The player.

statusstringbodyrequired

"start", "complete" or "fail".

pathstringbodyrequired

What was attempted, such as "World1:Level3". Cut to 128 characters.

scorenumberbody

Optional, finite.

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

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.

#TrackCurrencyEarned

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

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

playerPlayerbodyrequired

The player who received the currency.

currencystringbodyrequired

Currency key, at most 32 characters.

amountnumberbodyrequired

Greater than 0 and finite.

sourcestringbody

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

itemstringbody

What earned it. At most 64 characters.

balancenumberbody

The balance after the change. Finite.

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

#TrackCurrencySpent

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.

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

#TrackBalance

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

Records a $balance snapshot without a change.

playerPlayerbodyrequired

The player.

currencystringbodyrequired

Currency key.

balancenumberbodyrequired

The current balance. Finite; zero and negative values are allowed.

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

#TrackCurrencyTransfer

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.

fromPlayerbodyrequired

The sender.

toPlayer | numberbodyrequired

The receiver, as a Player or a positive user id.

currencystringbodyrequired

Currency key.

amountnumberbodyrequired

Greater than 0 and finite.

reasonstringbody

Such as "Trade" or "Gift". At most 64 characters.

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.

#WrapProcessReceipt

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

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

handlerfunctionbodyrequired

Your existing handler. Anything else raises WrapProcessReceipt expects your ProcessReceipt function. This is the only SDK function that can raise an error.

returnsfunction

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.

local MarketplaceService = game:GetService("MarketplaceService")

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

#SetProductNames

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 }bodyrequired

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.

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; they can be used in segments and drive player banners. They aren't affected by any tracking switch.

#SetPlayerProperty

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

The player.

keystringbodyrequired

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>.

valuestring | number | booleanbodyrequired

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

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

#SetPlayerProperties

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.

playerPlayerbodyrequired

The player.

propertiestablebodyrequired

Key to value, with the same rules as SetPlayerProperty.

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

#SetPlayerRole

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.

playerPlayerbodyrequired

The player.

rolestringbodyrequired

The role, such as "Moderator". Cut to 256 characters.

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

#Experiments

#GetVariant

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.

playerPlayerbodyrequired

The player. Anything else returns nil, nil.

experimentKeystringbodyrequired

The experiment's key from the dashboard.

variantstring?

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.

configtable?

The variant's config from the dashboard, or nil with variant.

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

#Fields

Analytics.Versionstring

The module's version, "1.0.0". Sent with every batch and shown as SDK version in the debugger.

Analytics.ServerKeystring

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.

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

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?,
}