@molecule/app-analytics

Core interface · analytics · App (browser) · v1.1.4 · Apache-2.0

Frontend analytics interface for molecule.dev

npm install @molecule/app-analytics

npm · Source on GitHub

How it works

@molecule/app-analytics is the analytics core interface on the app (browser) side: the API your app calls, with no vendor inside.

Choose the implementation by bonding one of its 2 providers: @molecule/app-analytics-mixpanel, @molecule/app-analytics-posthog.

import { identify, reset, setProvider, track } from '@molecule/app-analytics'
import { createProvider } from '@molecule/app-analytics-posthog'

// At startup — the key comes from your build-time env (in Vite:
// import.meta.env.VITE_POSTHOG_KEY); a missing key yields a warning +
// no-op provider, never a crash.
setProvider(createProvider({ apiKey: posthogApiKey }))

identify({ userId: user.id, email: user.email }) // on login
track({ name: 'order_placed', properties: { total } })
reset() // on logout

Providers (2): @molecule/app-analytics-mixpanel, @molecule/app-analytics-posthog

Works with: @molecule/app-bond, @molecule/app-logger

Reference

Frontend analytics interface for molecule.dev.

Provides a unified analytics API that can be backed by different implementations (PostHog, Mixpanel, etc.).

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { identify, reset, setProvider, track } from '@molecule/app-analytics'
import { createProvider } from '@molecule/app-analytics-posthog'

// At startup — the key comes from your build-time env (in Vite:
// import.meta.env.VITE_POSTHOG_KEY); a missing key yields a warning +
// no-op provider, never a crash.
setProvider(createProvider({ apiKey: posthogApiKey }))

identify({ userId: user.id, email: user.email }) // on login
track({ name: 'order_placed', properties: { total } })
reset() // on logout

Type

core

Installation

npm install @molecule/app-analytics @molecule/app-bond @molecule/app-logger

API

Interfaces

AnalyticsAuthUser

The default auth profile: an immutable id plus the traits analytics records.

An app whose auth client carries its OWN profile (no id) still auto-tracks auth events — it passes identifyUser to say which field identifies the user (see AutoTrackingOptions).

interface AnalyticsAuthUser {
  /** Unique user identifier. */
  id: string
  /** User email address. */
  email?: string
  /** User display name. */
  name?: string
}

AutoTrackingOptions

Auto-tracking sources and the identity adapter. Pass any combination of sources — only provided sources are tracked. Works for both web and mobile apps.

TUser is the profile the auth client hands to its listeners. The default, AnalyticsAuthUser, has an id, and it is identified by that field with no extra wiring. An app whose profile has no id (e.g. { username, email, bio }) passes an identifyUser extractor; it is REQUIRED for such a profile, so a client cannot be wired into tracking with no identity at all and userId: undefined never reaches a provider. That requirement is applied by setupAutoTracking's parameter (see IdentityRequirement), not by this interface, so the options bag stays declaration-mergeable:

declare module '@molecule/app-analytics' {
  interface AutoTrackingOptions {
    label?: string
  }
}
interface AutoTrackingOptions<TUser extends object = AnalyticsAuthUser> {
  /** Auth client for login/logout/register/error events. */
  authClient?: AuthClientLike<TUser>
  /**
   * Which field of the profile identifies the user in analytics — required when
   * the profile has no `id: string`. The default reads `id`, `email` and `name`.
   * Return `null` when the session has no stable identity: the sign-in is still
   * tracked, without an `identify` call or a `userId`.
   */
  identifyUser?: IdentifyUser<TUser>
  /** Router for page view tracking. */
  router?: RouterLike
  /** HTTP client for error tracking. */
  httpClient?: HttpClientLike
  /** Lifecycle client for app foreground/background and deep link tracking. */
  lifecycleClient?: LifecycleClientLike
  /** Push client for notification received/tapped tracking. */
  pushClient?: PushClientLike
}

AnalyticsUserProps

User properties for analytics identification.

interface AnalyticsUserProps {
  /** Unique user identifier. */
  userId: string
  /** User email address. */
  email?: string
  /** User display name. */
  name?: string
  /** Arbitrary key-value traits to associate with the user. */
  traits?: Record<string, unknown>
}

AnalyticsEvent

Event properties for analytics tracking.

interface AnalyticsEvent {
  /** Event name (e.g. `"button_clicked"`, `"purchase_completed"`). */
  name: string
  /** Arbitrary key-value properties for this event. */
  properties?: Record<string, unknown>
  /**
   * Event timestamp (defaults to now). Only honored where the underlying
   * browser SDK supports client-set timestamps (PostHog does); the Mixpanel
   * browser SDK always stamps the time of capture. For reliable historical
   * timestamps use the API-side `@molecule/api-analytics` bonds.
   */
  timestamp?: Date
  /**
   * Identified user who triggered the event. Browser analytics SDKs attribute
   * events to the AMBIENT identified session — call `identify()` first;
   * current browser bonds do not honor a per-event userId override. (Exists
   * for interface parity with `@molecule/api-analytics`, where there is no
   * ambient session and per-event IDs are required.)
   */
  userId?: string
  /**
   * Anonymous identifier for unauthenticated users. Like `userId`, browser
   * bonds use the SDK's own ambient anonymous identity instead of this field.
   */
  anonymousId?: string
}

AnalyticsPageView

Page view event.

interface AnalyticsPageView {
  /** Page name (e.g. `"Home"`, `"Settings"`). */
  name?: string
  /** Page category (e.g. `"Dashboard"`, `"Marketing"`). */
  category?: string
  /** Full page URL. */
  url?: string
  /** Page path (e.g. `"/settings/profile"`). */
  path?: string
  /** Referrer URL. */
  referrer?: string
  /** Arbitrary key-value properties for this page view. */
  properties?: Record<string, unknown>
}

AnalyticsProvider

Analytics provider interface that all analytics bond packages must implement.

interface AnalyticsProvider {
  /**
   * Identifies a user and associates traits with them.
   *
   * @param user - User properties including userId and optional traits.
   */
  identify(user: AnalyticsUserProps): Promise<void>

  /**
   * Tracks a named event with optional properties.
   *
   * @param event - The event name and properties to track.
   */
  track(event: AnalyticsEvent): Promise<void>

  /**
   * Records a page view.
   *
   * @param pageView - Page view details (name, path, properties).
   */
  page(pageView: AnalyticsPageView): Promise<void>

  /**
   * Associates a user with a group (e.g. company, team).
   *
   * @param groupId - The group identifier.
   * @param traits - Arbitrary traits to associate with the group.
   */
  group?(groupId: string, traits?: Record<string, unknown>): Promise<void>

  /**
   * Resets the current user identity and generates a new anonymous ID.
   */
  reset?(): Promise<void>

  /**
   * Flushes any queued events to the analytics service immediately.
   */
  flush?(): Promise<void>
}

Types

IdentifyUser

Maps a signed-in profile to the identity analytics records for it.

Return null when this session has no stable identity to record (an anonymous or throwaway session): the sign-in is then tracked without an identify call instead of sending an undefined userId.

type IdentifyUser<TUser> = (user: TUser) => AnalyticsUserProps | null

IdentityRequirement

The identity rule for one profile: a profile with id: string may omit identifyUser, a profile without one must pass it. Applied to setupAutoTracking's parameter so AutoTrackingOptions stays an interface that apps can augment.

type IdentityRequirement<TUser extends object> = [TUser] extends [{ id: string }]
  ? { identifyUser?: IdentifyUser<TUser> }
  : { identifyUser: IdentifyUser<TUser> }

Functions

setupAutoTracking(options)

Sets up automatic analytics tracking for auth events, route changes, HTTP errors, app lifecycle transitions, push notifications, and deep links. Returns a cleanup function that removes all subscriptions.

Pass any combination of sources — only provided sources are tracked.

The analytics provider is resolved at EVENT time, not at setup time — so setupAutoTracking() may safely run before the analytics bond is set (events fired before bonding no-op; events fired after are tracked).

The default-profile call takes an inline getClient(): it is typed as the default AnalyticsAuthUser, so identifyUser stays optional exactly as before. An app whose client carries its own profile names that profile — either on the auth client and an identifyUser extractor, or as the setup's type argument — and a profile with no id: string must pass identifyUser.

function setupAutoTracking(options: AutoTrackingOptions<AnalyticsAuthUser>): () => void
  • options — Sources to auto-track.

Returns: A cleanup function that removes all event subscriptions.

setProvider(provider)

Registers an analytics provider as the active singleton. Every payload is credential-redacted before the provider can emit it, regardless of which public analytics entrypoint produced it.

function setProvider(provider: AnalyticsProvider): void
  • provider — The analytics provider implementation to bond.

getProvider()

Retrieves the bonded analytics provider. Returns a no-op provider if none is bonded, so analytics calls never throw.

function getProvider(): AnalyticsProvider

Returns: The bonded analytics provider, or a silent no-op fallback.

hasProvider()

Checks whether an analytics provider is currently bonded.

function hasProvider(): boolean

Returns: true if an analytics provider is bonded.

identify(user)

Identifies the current user for analytics tracking. Errors are logged at debug level and ignored.

function identify(user: AnalyticsUserProps): Promise<void>
  • user — The user properties (ID, email, name, traits).

Returns: A promise that resolves when identification completes or the failure is logged at debug and ignored.

track(event)

Tracks a named event with optional properties. Errors are logged at debug level and ignored.

function track(event: AnalyticsEvent): Promise<void>
  • event — The event to track (name and optional properties).

Returns: A promise that resolves when tracking completes or the failure is logged at debug and ignored.

page(pageView)

Tracks a page view event. Errors are logged at debug level and ignored.

function page(pageView: AnalyticsPageView): Promise<void>
  • pageView — The page view data (name, path, referrer, etc.).

Returns: A promise that resolves when page tracking completes or the failure is logged at debug and ignored.

group(groupId, traits)

Associates the current user with a group/organization. Errors are logged at debug level and ignored.

function group(groupId: string, traits?: Record<string, unknown>): Promise<void>
  • groupId — The group identifier.
  • traits — Optional traits describing the group.

Returns: A promise that resolves when group association completes or the failure is logged at debug and ignored.

reset()

Resets the analytics state (e.g. on logout). Errors are logged at debug level and ignored.

function reset(): Promise<void>

Returns: A promise that resolves when reset completes or the failure is logged at debug and ignored.

flush()

Flushes any queued analytics events to the backend. Errors are logged at debug level and ignored.

function flush(): Promise<void>

Returns: A promise that resolves when flush completes or the failure is logged at debug and ignored.

snapshotAnalyticsSdkUrls(payload)

Copy an SDK-built payload into inert data immediately before its transport. Credential-named fields are redacted at any depth without invoking their accessors. Plain objects and arrays are detached; functions are dropped, while enumerable class fields and toJSON results are materialized once as inert data. Serialized strings retain safe components and ordinary identifiers.

The SDK itself owns only root/direct-property identifiers: the project token/$token, distinct/device/session/user/group IDs and UUIDs. A nested app trait named token or session_id is therefore still redacted. SDK-derived referring domains retain authority context, so username-only userinfo is removed while an ordinary email address is unchanged.

function snapshotAnalyticsSdkUrls<T>(payload: T): T
  • payload — A PostHog CaptureResult, Mixpanel hook payload, or compatible value.

Returns: A detached data-only payload with credential and URL values scrubbed.

Available Providers

ProviderPackage
Mixpanel@molecule/app-analytics-mixpanel
PostHog@molecule/app-analytics-posthog

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-bond ^1.0.1
  • @molecule/app-logger ^1.0.4

Runtime Dependencies

  • @molecule/app-bond

  • @molecule/app-logger

  • Every convenience function (track, identify, page, …) swallows provider errors and no-ops when nothing is bonded — analytics can never break the UI, so hasProvider() is the ONLY signal that separates "analytics disabled/unbonded" from "events are being tracked". Check it (and the bond's own console warning) before debugging tracking code.

  • Attribution is AMBIENT in the browser: call identify(user) on login and reset() on logout; per-event userId/anonymousId fields are not honored by browser bonds (they exist for parity with @molecule/api-analytics).

  • group(groupId) normalizes the group TYPE to 'company' in every bond (Mixpanel group key, PostHog group type) — look under "company" in the provider's UI.