React Analytics SDK

API reference for @temps-sdk/react-analytics, documented for version 0.0.4. Wrap your app in TempsAnalyticsProvider and it tracks pageviews, page exits, Web Vitals and engagement automatically; the hooks below add custom events and control session recording.

For what the data looks like in the dashboard, see Analytics; for a step-by-step setup, follow Add analytics, errors and session replay. Other SDKs are listed in SDKs.


Installation

npm install @temps-sdk/react-analytics

Requirements: React 18+ or React 19


TempsAnalyticsProvider

The root provider component. Wrap your application with it to enable analytics.

import { TempsAnalyticsProvider } from '@temps-sdk/react-analytics';

<TempsAnalyticsProvider basePath="/api/_temps">
  {children}
</TempsAnalyticsProvider>

Props

  • Name
    basePath
    Type
    string
    Description

    API endpoint path. When deployed on Temps, the proxy handles this automatically.

  • Name
    domain
    Type
    string
    Description

    Override the detected hostname. Use when not deployed on Temps or running locally.

  • Name
    disabled
    Type
    boolean
    Description

    Kill switch to disable all analytics.

  • Name
    ignoreLocalhost
    Type
    boolean
    Description

    Skip tracking on localhost, 127.0.0.1, and test environments.

  • Name
    autoTrackPageviews
    Type
    boolean
    Description

    Automatically track page views on pushState and popstate events.

  • Name
    autoTrackPageLeave
    Type
    boolean
    Description

    Track page_leave events with time-on-page via pagehide and beforeunload.

  • Name
    pageLeaveEventName
    Type
    string
    Description

    Custom event name for page leave tracking.

  • Name
    autoTrackSpeedAnalytics
    Type
    boolean
    Description

    Collect Web Vitals: the Core Web Vitals (LCP, INP, CLS), plus FCP, TTFB and FID (deprecated, still collected).

  • Name
    autoTrackEngagement
    Type
    boolean
    Description

    Enable heartbeat-based engagement tracking.

  • Name
    heartbeatInterval
    Type
    number
    Description

    Engagement heartbeat interval in milliseconds.

  • Name
    inactivityTimeout
    Type
    number
    Description

    Milliseconds of no interaction before marking the user as inactive.

  • Name
    engagementThreshold
    Type
    number
    Description

    Milliseconds on page before the user is considered "engaged".

  • Name
    enableSessionRecording
    Type
    boolean
    Description

    Enable rrweb-based session recording. Off by default; see Session Replay.

  • Name
    sessionRecordingConfig
    Type
    SessionRecordingConfig
    Description

    Configuration object for session recording. See Session Recording Configuration.


useTempsAnalytics

The core analytics hook. Returns the full analytics context.

import { useTempsAnalytics } from '@temps-sdk/react-analytics';

const { trackEvent, trackPageview, identify, enabled } = useTempsAnalytics();

Return value

  • Name
    trackEvent
    Type
    (name: string, data?: Record<string, JsonValue>) => Promise<void>
    Description

    Send a custom event with optional properties.

  • Name
    trackPageview
    Type
    () => void
    Description

    Manually fire a pageview event.

  • Name
    identify
    Type
    (userId: string, traits?: Record<string, JsonValue>) => Promise<void> | void
    Description

    Placeholder kept for SDK parity; it does nothing in 0.0.4. To attach a user to a visitor, enrich the visitor from your backend with the Node SDK.

  • Name
    enabled
    Type
    boolean
    Description

    Whether analytics are currently active.


useTrackEvent

Convenience hook that returns only the trackEvent function.

import { useTrackEvent } from '@temps-sdk/react-analytics';

const track = useTrackEvent();
track('button_clicked', { id: 'cta-hero' });

useTrackPageview

Returns a function to manually trigger a pageview.

import { useTrackPageview } from '@temps-sdk/react-analytics';

const trackPageview = useTrackPageview();
useEffect(() => { trackPageview(); }, []);

usePageLeave

Track when users leave a page, including time spent.

import { usePageLeave } from '@temps-sdk/react-analytics';

const { triggerPageLeave } = usePageLeave({
  eventName: 'article_leave',
  eventData: { category: 'blog' },
  enabled: true,
});

Options

  • Name
    eventName
    Type
    string
    Description

    Event name for the page leave event.

  • Name
    eventData
    Type
    Record<string, JsonValue>
    Description

    Additional data merged into the event payload.

  • Name
    enabled
    Type
    boolean
    Description

    Enable or disable tracking.

Return value

  • Name
    triggerPageLeave
    Type
    () => void
    Description

    Manually trigger a page leave event (e.g. before client-side navigation).

The event payload automatically includes time_on_page_ms, url, referrer, and timestamp.


useSpeedAnalytics

Tracks Web Vitals performance metrics. Enabled by default through the provider.

import { useSpeedAnalytics } from '@temps-sdk/react-analytics';

useSpeedAnalytics({ basePath: '/api/_temps', disabled: false });

Metrics collected:

MetricFull nameWhat it measures
TTFBTime to First ByteServer responsiveness
FCPFirst Contentful PaintFirst pixels rendered
LCPLargest Contentful PaintMain content visible (Core Web Vital)
FIDFirst Input DelayFirst-input delay (deprecated: INP replaced it as a Core Web Vital in March 2024)
CLSCumulative Layout ShiftVisual stability (Core Web Vital)
INPInteraction to Next PaintOverall responsiveness (Core Web Vital)

Initial metrics (TTFB, FCP, LCP, FID) are batched into a single request. Late metrics (CLS, INP) are sent individually as they stabilize.


useEngagementTracking

Manual engagement tracking for specific pages or components.

import { useEngagementTracking } from '@temps-sdk/react-analytics';

const { engagementData, isTracking } = useEngagementTracking({
  heartbeatInterval: 15000,
  engagementThreshold: 5000,
  onEngagementUpdate: (data) => console.log(data),
  onPageLeave: (data) => console.log(data),
});

Engagement data shape

interface EngagementData {
  engagement_time_seconds: number;
  total_time_seconds: number;
  heartbeat_count: number;
  is_engaged: boolean;
  is_visible: boolean;
  time_since_last_activity: number;
}

useScrollVisibility

Track when elements scroll into view using Intersection Observer.

import { useScrollVisibility } from '@temps-sdk/react-analytics';

const ref = useScrollVisibility({
  eventName: 'pricing_viewed',
  eventData: { section: 'pricing' },
  threshold: 0.75,
  once: true,
});

return <section ref={ref}>Pricing Plans</section>;

Options

  • Name
    eventName
    Type
    string
    Description

    Event name to fire when the element is visible.

  • Name
    eventData
    Type
    Record<string, JsonValue>
    Description

    Additional event properties.

  • Name
    threshold
    Type
    number
    Description

    Visibility percentage (0.0 to 1.0) required to trigger.

  • Name
    once
    Type
    boolean
    Description

    Track only the first time the element becomes visible.

  • Name
    enabled
    Type
    boolean
    Description

    Enable or disable tracking.

  • Name
    root
    Type
    Element | null
    Description

    Scroll container (null = viewport).

  • Name
    rootMargin
    Type
    string
    Description

    Margin around the root element.


useSessionRecording

Control session recording programmatically.

import { useSessionRecording } from '@temps-sdk/react-analytics';

const {
  isRecordingEnabled,
  enableRecording,
  disableRecording,
  toggleRecording,
  sessionId,
} = useSessionRecording();

Return value

  • Name
    isRecordingEnabled
    Type
    boolean
    Description

    Whether recording is currently active.

  • Name
    enableRecording
    Type
    () => void
    Description

    Start recording. The choice is saved in localStorage, so use this for consent flows.

  • Name
    disableRecording
    Type
    () => void
    Description

    Stop recording.

  • Name
    toggleRecording
    Type
    () => void
    Description

    Toggle recording on/off.

  • Name
    sessionId
    Type
    string | null
    Description

    The current session ID if recording.


Declarative tracking

Track click events without writing JavaScript using HTML attributes:

<button temps-event-name="cta_click" temps-data-section="hero" temps-data-variant="blue">
  Get Started
</button>

Any element with temps-event-name fires an event on click. All temps-data-* attributes are sent as event properties (with the temps-data- prefix stripped).


Session recording configuration

Pass to the provider as sessionRecordingConfig. Privacy controls, consent patterns and the replay CLI are covered in Session Replay:

  • Name
    sessionSampleRate
    Type
    number
    Description

    Percentage of sessions to record (0.0 to 1.0). Use 0.1 for 10%.

  • Name
    maskAllInputs
    Type
    boolean
    Description

    Replace all input field values with asterisks. Password and email fields are always masked.

  • Name
    maskTextSelector
    Type
    string
    Description

    CSS selector for text elements to mask.

  • Name
    blockClass
    Type
    string
    Description

    CSS class to completely hide elements from recordings.

  • Name
    ignoreClass
    Type
    string
    Description

    CSS class whose input events are not recorded (the element itself still appears).

  • Name
    maskTextClass
    Type
    string
    Description

    CSS class to mask text content.

  • Name
    excludedPaths
    Type
    string[]
    Description

    URL paths to exclude from recording. Supports wildcards (e.g. /admin/*). The React provider has no built-in exclusions, so list sign-in, checkout and payment routes here.

  • Name
    recordCanvas
    Type
    boolean
    Description

    Record canvas element content.

  • Name
    collectFonts
    Type
    boolean
    Description

    Collect font data for accurate replay.

  • Name
    batchSize
    Type
    number
    Description

    Number of events per batch before sending.

  • Name
    flushInterval
    Type
    number
    Description

    Maximum time (ms) before flushing a batch.


Environment detection

When ignoreLocalhost is true (default), the SDK disables itself in:

EnvironmentDetection
Localhostlocalhost, 127.0.0.1, ::1, *.local
Test runnersjest, mocha, vitest, cypress globals detected
Manual overridelocalStorage.temps_ignore = "true"

TypeScript exports

All types are exported:

import type {
  AnalyticsContextValue,
  TempsAnalyticsProviderProps,
  EngagementData,
  EngagementTrackerOptions,
  WebVitalMetric,
  SpeedMetric,
  JsonValue,
} from '@temps-sdk/react-analytics';

Last updated

Was this page helpful?