@molecule/app-analytics
Core interface · analytics · App (browser) · v1.0.2 · Apache-2.0
Frontend analytics interface for molecule.dev
npm install @molecule/app-analyticsHow 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 logoutProviders (2): @molecule/app-analytics-mixpanel, @molecule/app-analytics-posthog
Works with: @molecule/app-bond
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.tsJSDoc, 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
API
Interfaces
AutoTrackingOptions
Auto-tracking options. Pass any combination of sources — only provided sources are tracked. Works for both web and mobile apps.
interface AutoTrackingOptions {
/** Auth client for login/logout/register/error events. */
authClient?: AuthClientLike
/** 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>
}
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).
function setupAutoTracking(options: AutoTrackingOptions): () => 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.
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 silently ignored.
function identify(user: AnalyticsUserProps): Promise<void>
user— The user properties (ID, email, name, traits).
Returns: A promise that resolves when identification completes or fails silently.
track(event)
Tracks a named event with optional properties. Errors are silently 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 fails silently.
page(pageView)
Tracks a page view event. Errors are silently 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 fails silently.
group(groupId, traits)
Associates the current user with a group/organization. Errors are silently 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 fails silently.
reset()
Resets the analytics state (e.g. on logout). Errors are silently ignored.
function reset(): Promise<void>
Returns: A promise that resolves when reset completes or fails silently.
flush()
Flushes any queued analytics events to the backend. Errors are silently ignored.
function flush(): Promise<void>
Returns: A promise that resolves when flush completes or fails silently.
Available Providers
| Provider | Package |
|---|---|
| Mixpanel | @molecule/app-analytics-mixpanel |
| PostHog | @molecule/app-analytics-posthog |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1
Runtime Dependencies
-
@molecule/app-bond -
Every convenience function (
track,identify,page, …) swallows provider errors and no-ops when nothing is bonded — analytics can never break the UI, sohasProvider()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 andreset()on logout; per-eventuserId/anonymousIdfields 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.