@fluidattacks/tracks
This library provides a convenient way to report usage analytics from any TypeScript or JavaScript application.
All operations run in the background, and errors are logged but don't propagate to the caller, ensuring your application's flow isn't interrupted.
Usage
import { Tracks } from "@fluidattacks/tracks";
const client = new Tracks();
client.event.create({
action: "CREATE",
author: "author",
date: new Date(),
mechanism: "API",
metadata: { foo: "bar" },
object: "object",
objectId: "objectId",
});
Anonymous visitors
For unauthenticated surfaces, set the identity once on the client so no call
site can omit it. The cookie is issued HttpOnly, so minting it and reading it
back belong on the server.
import {
Tracks,
createAnonymousId,
nextSessionId,
readAnonymousCookie,
serializeAnonymousCookie,
} from "@fluidattacks/tracks";
const COOKIE_NAME = "my_anon_id";
const anonymousId =
readAnonymousCookie(cookieHeader, { name: COOKIE_NAME }) ??
createAnonymousId();
const cookie = serializeAnonymousCookie(anonymousId, {
domain: ".example.com",
name: COOKIE_NAME,
});
const client = new Tracks({
author: anonymousId,
authorAnonymous: true,
sessionId: nextSessionId(previousSessionId, lastSeenAt, new Date()),
});
cookieHeader is the incoming Cookie header; previousSessionId and
lastSeenAt are whatever the caller persisted. The session id rolls over after
30 minutes of inactivity.
Build that client per request. A client carrying an identity belongs to a single visitor, so a module level one would hand the first visitor id to everyone else the process serves.
author and authorAnonymous travel as a pair: an event that supplies its own
author is never marked anonymous by the client identity. The API still
defaults author_anonymous to true when the field is absent, and its public
route only accepts anonymous events, so a client cannot record an identified
author on its own.
mechanism is always required per event: the SDK never guesses it, because a
wrong mechanism is indistinguishable from a real one in the analytics.