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
pushStateandpopstateevents.
- Name
autoTrackPageLeave- Type
- boolean
- Description
When
autoTrackEngagementisfalse, track page-exit events with time-on-page viapagehideandbeforeunload.
- Name
pageLeaveEventName- Type
- string
- Description
Custom event name for the legacy page-exit tracker (
autoTrackEngagement={false}). The engagement tracker usespage_leave.
- 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.
Page-exit options in SDK 0.0.7: with the default autoTrackEngagement={true}, the engagement tracker sends page_leave events on navigation and unload. That branch does not use autoTrackPageLeave or pageLeaveEventName. To disable automatic page-exit events, disable both trackers (this also disables engagement heartbeats):
<TempsAnalyticsProvider autoTrackEngagement={false} autoTrackPageLeave={false}>
{children}
</TempsAnalyticsProvider>
For a custom exit event name, set autoTrackEngagement={false} and leave autoTrackPageLeave enabled; pageLeaveEventName then names the legacy pagehide/beforeunload event. It does not add route-change exit tracking.
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.
The provider already tracks the initial pageview and pathname changes by default.
Before using a manual pageview effect like the one below, set
autoTrackPageviews={false} on your existing TempsAnalyticsProvider to avoid
counting the same visit twice. For standard Next.js routing, keep automatic
tracking and omit the manual effect.
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:
| Metric | Full name | What it measures |
|---|---|---|
| TTFB | Time to First Byte | Server responsiveness |
| FCP | First Contentful Paint | First pixels rendered |
| LCP | Largest Contentful Paint | Main content visible (Core Web Vital) |
| FID | First Input Delay | First-input delay (deprecated: INP replaced it as a Core Web Vital in March 2024) |
| CLS | Cumulative Layout Shift | Visual stability (Core Web Vital) |
| INP | Interaction to Next Paint | Overall 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
Read and update the recording preference exposed by SessionRecordingProvider.
In @temps-sdk/react-analytics 0.0.7, this hook and the recorder inside TempsAnalyticsProvider use separate state. Calling enableRecording, disableRecording or toggleRecording updates the hook state and, by default, its stored preference, but does not start or stop the mounted recorder. isRecordingEnabled is not proof of recorder activity. Do not rely on these methods for consent withdrawal; see Consent and privacy compliance.
import { useSessionRecording } from '@temps-sdk/react-analytics';
const {
isRecordingEnabled,
enableRecording,
disableRecording,
toggleRecording,
sessionId,
} = useSessionRecording();
Return value
- Name
isRecordingEnabled- Type
- boolean
- Description
The hook's recording preference; not the mounted recorder's activity.
- Name
enableRecording- Type
- () => void
- Description
Set the hook preference to enabled and persist it in
localStorageby default. In 0.0.7 this does not start the mounted recorder.
- Name
disableRecording- Type
- () => void
- Description
Set the hook preference to disabled. In 0.0.7 this does not stop the mounted recorder.
- Name
toggleRecording- Type
- () => void
- Description
Toggle the hook preference. In 0.0.7 this does not toggle the mounted recorder.
- Name
sessionId- Type
- string | null
- Description
The session ID read from storage when the hook preference changes; not confirmation of active 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/*). In React SDK 0.0.7, these are added to the shared built-in authentication and payment exclusions, including/login,/signup,/checkout*,/payment*and/billing*. Add your application-specific sensitive routes here. Versions 0.0.4 and earlier have no built-in list.
- 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:
| Environment | Detection |
|---|---|
| Localhost | localhost, 127.0.0.1, ::1, *.local |
| Test runners | jest, mocha, vitest, cypress globals detected |
| Manual override | localStorage.temps_ignore = "true" |
TypeScript exports
All types are exported:
import type {
AnalyticsContextValue,
TempsAnalyticsProviderProps,
EngagementData,
EngagementTrackerOptions,
WebVitalMetric,
SpeedMetric,
JsonValue,
} from '@temps-sdk/react-analytics';