📦 SwiftyLaunch Modules
⚙️ BackendKit
AnalyticsKit Integration

AnalyticsKit Integration in BackendKit

AnalyticsKit Integration

Easily track your backend logs and errors using our pre-built AnalyticsKit functions.

Basic Usage

Import AnalyticsKit

To use AnalyticsKit functions, you first need to include Analytics in your file.

import * as Analytics from "./AnalyticsKit/Analytics";

Definitions

Now you can track events in your backend code using the captureEvent function.

Function Definition

Analytics.ts
export async function captureEvent({
  data,
  fromUserID,
}: {
  data: EventData;
  fromUserID?: string;
}) {}
  • data: The event data you want to track. (See definition below)
  • fromUserID (Optional): The user ID from which the event originated. If the event is not related to any particular user, you can omit this parameter.

Event Data Definiton

The Event Data object contains the information that will be sent to PostHog. See analogous definition on the client-side here.

Analytics.ts
type EventData = {
  eventType: "info" | "error" | "success";
  id: string;
  longDescription?: string;
  source: "general" | "auth" | "db" | "analytics" | "iap" | "notif" | "aikit";
  relevancy?: "low" | "medium" | "high";
};
  • eventType: The type of the event, can be .info, .error, .success, This will be prefixed in the resulting event id. See example below.
  • id: A unique identifier for the event. Snake Case recommended, Example: fetching_user_data.
  • longDescription (Optional): A longer description of the event. Example: Couldn't fetch user info because user is not authenticated.
  • source: The source of the event. What caused it. Example: .auth, .iap.
  • relevancy (Optional): The relevancy of the event. Example: .low, .medium, .high. Defaults to .medium, and to .high when the event is of type .error.

Usage Example

Capturing an Event

This example captures an event and sends it to PostHog when the fetchAllUsers function is called.

index.ts
export const fetchAllUsers = onCall(async (request) => {
  // get user ID from request (if available)
  let fromUid = request.auth?.uid;
 
  Analytics.captureEvent({
    data: {
      eventType: "info",
      id: "fetch_all_users",
      longDescription: "Fetching all users from the database",
      source: "db",
    },
    fromUserID: fromUid,
  });
 
  // execute the function
});

In the PostHog Dashboard

When the fetchAllUsers function is executed, we'll see the following event in the PostHog Dashboard:

PostHog Dashboard from Example