Swetrix

Tracking script reference

The Swetrix.js is a highly customisable tracking script. The following is a reference of all the available functions and options it provides.

init()

This function is used to initialise the analytics. Basically you're letting the script know which project do you want to use it with, as well as specifying your custom parameters if needed.

It takes two arguments:

  1. projectID - the ID of the project you want to use it with.
  2. options - an object with custom options.

Here's an example of how to use this function with all the available options:

swetrix.init("YOUR_PROJECT_ID", {
  devMode: false,
  disabled: false,
  respectDNT: false,
  apiURL: "https://api.swetrix.com/log",
  profileId: "user-123",
  preloadSessionReplay: true,
});
NameDescriptionDefault value
devModeWhen set to true, localhost events will be sent to server.false
disabledWhen set to true, the tracking library won't send any data to server.
Useful for development purposes when this value is set based on '.env' var.
false
respectDNTBy setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting.
This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances.
false
apiURLIf you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like [BASE_URL]/backend/v1/log.'https://api.swetrix.com/log'
profileIdOptional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices.undefined
preloadSessionReplaySet to true to preload the session replay recorder after init(), or pass { rrwebUrl: "https://example.com/rrweb.min.js" } to load it from a custom URL. Recording only starts after you call startSessionReplay().undefined

track()

It is important to ensure that no Personal Data that could identify a specific individual is transmitted in a metadata or custom event name field. Personally identifiable information (PII) is any information that can uniquely identify an individual, including full name, email address, phone number, credit card number, etc. All other information is anonymised.

With this function you can track any custom events you want. You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name. The total number of track calls and their conversion rate will be saved.

Here's an example of how to use this function with all the available options:

swetrix.track({
  ev: "YOUR_EVENT_NAME",
  unique: false,
  profileId: "user-123",
});
NameDescriptionDefault value
evThe event identifier you want to track. Can contain any characters (including spaces, unicode, etc.) with a maximum length of 256 characters.REQUIRED PARAMETER
uniqueIf true, only 1 event with the same ID will be saved per user session.
The principle of this parameter is similar to page views and unique views.
false
metaAn object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is 20 and the total length of the values combined must be less than 1000 characters.
This feature is useful if you want to track additional data about your custom events, for example the custom event name might be Sign up and the metadata might be { affiliate: 'Yes', footer: 'No' }.
{}
profileIdOptional profile ID for long-term user tracking. Overrides the global profileId if set.undefined

trackViews()

Calling trackViews will result in sending the data about the user to our servers. Such data will include the following params if available:

  1. pid - the unique Project ID request is related to.
  2. lc - users locale (e.g. en_US or uk_UA).
  3. tz - users timezone (e.g. Europe/Helsinki).
  4. ref - the URL of the previous webpage from which a page was opened.
  5. so - the page source ('ref' | 'source' | 'utm_source' GET param).
  6. me - UTM medium ('utm_medium' GET param).
  7. ca - UTM campaign ('utm_campaign' GET param).
  8. te - UTM term ('utm_term' GET param).
  9. co - UTM content ('utm_content' GET param).
  10. pg - the page user currently views (e.g. /hello).
  11. qs - the raw URL query string of the current page (without the leading ?). Used server-side to recover the traffic source from ad/social click IDs (gclid, fbclid, msclkid, ttclid, etc.) when the browser stripped the referrer. The raw query string is not stored — it's parsed for known click IDs and discarded. UTM parameters always take precedence. See Traffic sources for the full list of supported click IDs.
  12. perf - an object which contains performance metrics related to the page load.
  13. profileId - the profile ID if set.

On the server side we also gather users IP Address and User Agent. This data is used to detect whether the page view is unique or not.

We DO NOT store neither IP Address nor User Agent as a raw strings, such data is stored as a salted hash for no longer than 30 minutes or 12:00 AM UTC, whatever happens first.

After this timeframe the identifiable data is forever deleted from our servers.

Here's an example of how to use this function with all the available options:

swetrix.trackViews({
  unique: false,
  heartbeatOnBackground: false,
  hash: false,
  search: false,
  callback: undefined,
});
NameDescriptionDefault value
uniqueIf true, only unique events will be saved. This param is useful when tracking single-page landing websites.false
callbackA callback used to edit / prevent sending pageviews.
It accepts an object with pageview event data as a parameter which has the following structure:
lc: string | undefined
tz: string | undefined
ref: string | undefined
so: string | undefined
me: string | undefined
ca: string | undefined
te: string | undefined
co: string | undefined
qs: string | undefined
meta: object | undefined ("object" values must be string, number, boolean, null, or undefined)
pg: string | null | undefined
profileId: string | undefined

The callback is supposed to return the edited payload or false to prevent sending the pageview. If true is returned, the payload will be sent as-is.
undefined
heartbeatOnBackgroundSend Heartbeat requests when the website tab is not active in the browser.
Setting this to true means users who keep your website open in an inactive browser tab or window can still be counted in realtime statistics.
Setting this to true is usually useful for services like Spotify or Youtube.
false
hashSet to true to enable hash-based routing. For example if you have pages like /#/path or want to track pages like /path#hash.false
searchSet to true to enable search-based routing. For example if you have pages like /path?search. Although it's not recommended in most cases, you can set both hash and search to true at the same time, in which case the pageview event will be fired when either the hash or the search part of the URL changes (again, both the hash and the search are sent to the server).false

The trackViews function returns a Promise with an object with some methods allowing you to alter the behaviour of page tracking:

{
  // This function stops the tracking of pages.
  stop() {},
}

Noscript fallback

The /log/noscript image pixel records pageviews for visitors with JavaScript disabled. It accepts the required pid query parameter and an optional pg page path, for example / or /login. If pg is not provided, the API tries to recover it from the Referer header and stores only the URL pathname. If neither value is available, pg is stored as null and will be displayed in dashboard as Not set.

pageview()

This function is used to manually track a page view event. It's useful if your application uses esoteric routing which is not supported by Swetrix by default.

This function accepts an object argument, that contains the following properties:

  1. payload - an object that contains pageview payload. Accepts same values as the trackViews function callback property.
  2. (optional) unique - if set to true, only 1 event with the same ID will be saved per user session.

Here are some examples of how to use this function:

// Track a page view with a path '/hello'.
swetrix.pageview({
  payload: {
    pg: "/hello",
  },
});

// Track a page view with a path '/hello' and some metadata.
swetrix.pageview({
  payload: {
    pg: "/hello",
    lc: "de-DE",
    meta: {
      author: "Andrii",
      type: "story",
    },
    profileId: "user-123",
  },
});

trackErrors()

This function is used to enable automatic client-side error monitoring. It adds an error event listener on your site and when an error happens - send it to our APIs.

The data we collect includes the following params if available:

  1. pid - the unique Project ID request is related to.
  2. lc - users locale (e.g. en_US or uk_UA).
  3. tz - users timezone (e.g. Europe/Helsinki).
  4. pg - the page user currently views (e.g. /hello).
  5. name - error name (e.g. ParseError)
  6. message - error message (e.g. Malformed input)
  7. lineno / colno - on what line and column in your code did the error occur
  8. filename - in what file did the error occur
  9. stackTrace - the stack trace of the error (e.g. Uncaught Error\n at query (:10:11)\n at database (:6:5))
  10. meta - an object that contains event-related metadata. You can set it via a callback function.

Here's an example of how to use this function with all the available options:

swetrix.trackErrors({
  sampleRate: 1,
  callback: undefined,
});
NameDescriptionDefault value
sampleRateA number that indicates how many errors should be sent to the server. Accepts values between 0 and 1. For example, if set to 0.5 - only ~50% of errors will be sent to Swetrix. For testing, we recommend setting this value to 1. For production, you should configure it depending on your needs as each error event counts towards your plan.1
callbackA callback used to edit / prevent sending errors. It accepts an object which contains some information about the error (name, message, lineno, colno, filename, stackTrace), as well as some regular analytics info (lc, tz, pg, meta).
The callback is supposed to return the edited payload or false to prevent sending the error event. If true is returned, the payload will be sent as-is.
undefined

The trackErrors function returns an object with some methods allowing you to alter the behaviour of error tracking:

{
  // This function stops the tracking of errors.
  stop() {},
}

trackError()

This function is used to manually track an error event.

This function takes a payload object with the following fields:

  1. name - the error name (e.g. ParseError)
  2. (optional) message - error message (e.g. Malformed input)
  3. (optional) lineno - on what line in your code did the error occur (e.g. 1520)
  4. (optional) colno - on what column in your code did the error occur (e.g. 26)
  5. (optional) filename - in what file did the error occur (e.g. https://example.com/broken.js)
  6. (optional) stackTrace - the stack trace of the error (e.g. Uncaught Error\n at query (:10:11)\n at database (:6:5))
  7. (optional) meta - an object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is 100 and the total length of the values combined must be less than 2000 characters.

Here is an example of how to use this function:

swetrix.trackError({
  name: "ParseError",
  message: "Malformed input",
  lineno: 1520,
  colno: 26,
  filename: "https://example.com/broken.js",
  stackTrace: `Uncaught Error: Malformed input
    at query (:10:11)
    at database (:6:5)
    at controller (:2:5)`,
  meta: {
    level: "Critical",
  },
});

startSessionReplay()

This function starts recording the current browser session so you can watch it later in the Session Replays tab.

Session replays may capture page content, user interactions, and non-password input values depending on the privacy mode you choose. We recommend gating startSessionReplay() behind your consent flow where applicable, and not recording sensitive pages unless you have reviewed your masking settings, consent requirements, and legal basis for collecting this data.

Call startSessionReplay() after init(). If you set preloadSessionReplay: true in init(), Swetrix preloads the recorder first so starting a replay is faster. If you do not preload it, startSessionReplay() loads the recorder when it is called.

swetrix.init("YOUR_PROJECT_ID", {
  preloadSessionReplay: true,
});

const replay = await swetrix.startSessionReplay({
  privacy: "total",
  maskAllText: true,
  maxBytesPerChunk: 512 * 1024,
});

await replay.stop();

When using the npm package:

import { init, startSessionReplay } from "swetrix";

init("YOUR_PROJECT_ID", {
  preloadSessionReplay: true,
});

const replay = await startSessionReplay({
  privacy: "total",
  maskAllText: true,
  maxBytesPerChunk: 512 * 1024,
});

For npm installs, Swetrix dynamically imports the installed rrweb package only when the recorder is preloaded or started, so it can be split into an async chunk by your bundler. For script-tag installs, Swetrix loads the standalone replay recorder with an async script tag.

NameDescriptionDefault value
privacyControls how much page content is masked. Use total to mask all text and inputs and block media/canvas content, normal to mask all inputs, or none to only force password inputs to stay masked unless you add your own rrweb masking options.total
maskAllTextMasks all non-input text with asterisks. Defaults to true when privacy is total, and false for normal or none.privacy-based
rrwebAdvanced recorder options passed to rrweb.record(). If you provide an emit callback, Swetrix will call it and still upload replay events.undefined
flushIntervalMsHow often replay events are uploaded while recording.5000
maxEventsPerChunkThe maximum number of replay events to batch before Swetrix uploads a chunk immediately.100
maxBytesPerChunkThe approximate maximum byte size to buffer before Swetrix uploads a chunk immediately.524288
maxBytesPerEventDrops a single replay event if it is larger than this many bytes. This protects the visitor's browser and your replay storage from unusually large snapshots.5242880
recordIframesAllows iframe elements to be captured. Iframes are blocked by default to reduce replay size and avoid recording embedded third-party content.false

To mask text while keeping media less restricted than total privacy, combine normal privacy with maskAllText:

await swetrix.startSessionReplay({
  privacy: "normal",
  maskAllText: true,
});

By default, iframe elements are blocked from replay snapshots. If you own the iframe content and need it in the replay, opt in explicitly:

await swetrix.startSessionReplay({
  privacy: "normal",
  recordIframes: true,
});

Cross-origin iframe recording also requires rrweb's cross-origin iframe support and should only be enabled for domains you control:

await swetrix.startSessionReplay({
  recordIframes: true,
  rrweb: {
    recordCrossOriginIframes: true,
  },
});

The function returns a Promise with controls for the active replay:

{
  flush() {},
  stop() {},
}

flush() uploads any queued replay events immediately. stop() stops recording, flushes pending events, and ends the local recorder for this page.

Session replay tracking follows the same disabled, respectDNT, localhost, and automated-browser checks as regular analytics. On Swetrix Cloud, the project must also have session replays available on its plan and quota.

getFeatureFlags()

Fetches all feature flags for the project. Results are cached for 5 minutes by default. This cache is shared with experiment assignments.

On Swetrix Cloud, the project owner must be on Plus or Enterprise for feature flag evaluation. If the project is on a plan without Feature Flags, evaluation returns an empty result.

const flags = await swetrix.getFeatureFlags({
  profileId: "user-123",
});
// Returns: { 'flag-1': true, 'flag-2': false }

Arguments:

  1. options (optional): { profileId?: string }
  2. forceRefresh (optional): boolean - If true, bypasses the cache.

getFeatureFlag()

Gets the value of a single feature flag.

const isEnabled = await swetrix.getFeatureFlag("new-feature", {
  profileId: "user-123",
});

Arguments:

  1. key: string - The feature flag key.
  2. options (optional): { profileId?: string }
  3. defaultValue (optional): boolean - Default value if flag not found (default: false).

clearFeatureFlagsCache()

Clears the cached feature flags and experiments, forcing a fresh fetch on the next call.

swetrix.clearFeatureFlagsCache();

getExperiments()

Fetches variant assignments for running A/B test experiments that use default feature-flag exposure. Results are cached for 5 minutes by default and share the cache with feature flags.

On Swetrix Cloud, the project owner must be on Plus or Enterprise for experiment evaluation. Experiment assignments and feature flags are evaluated by the same request, so they share the same 5-minute cache. If the project is on a plan without Experiments, evaluation returns an empty result.

const experiments = await swetrix.getExperiments({
  profileId: "user-123",
});
// Returns: { 'experiment-1': 'variant-a', 'experiment-2': 'control' }

Arguments:

  1. options (optional): { profileId?: string }
  2. forceRefresh (optional): boolean - If true, bypasses the cache.

Calling this function records exposure for returned feature-flag-based experiments. If an experiment uses custom event exposure, send the configured custom event with track() when the visitor actually sees the experimental surface.

getExperiment()

Gets the variant key for a specific running A/B test experiment that uses default feature-flag exposure.

const variant = await swetrix.getExperiment("checkout-redesign-experiment-id", {
  profileId: "user-123",
});

Arguments:

  1. experimentId: string - The experiment ID.
  2. options (optional): { profileId?: string }
  3. defaultVariant (optional): string | null - Default variant if not found (default: null).

Like getExperiments(), this records exposure when a feature-flag-based assignment is returned.

Pass the optional third argument only when you want a fallback variant:

const variant = await swetrix.getExperiment(
  "checkout-redesign-experiment-id",
  { profileId: "user-123" },
  "control",
);

clearExperimentsCache()

Clears the cached experiment assignments. This is an alias for clearFeatureFlagsCache() because feature flags and experiments share the same evaluation cache.

swetrix.clearExperimentsCache();

getProfileId()

Gets the anonymous profile ID for the current visitor. If profileId was set via init, returns that. Otherwise, requests server to generate one from IP/UA hash.

This ID is commonly used for revenue attribution — pass it to your payment provider (swetrix_profile_id in Stripe metadata or Paddle customData) or include it in the request body when posting to /log/revenue to link transactions to specific visitors.

const profileId = await swetrix.getProfileId();

getSessionId()

Gets the current session ID for the visitor. Session IDs are generated server-side based on IP and user agent.

const sessionId = await swetrix.getSessionId();

On this page