Overview
Heap is a digital insights platform that automatically captures all user interactions without requiring manual event tracking. The Heap SDK provides autocapture capabilities that record clicks, form submissions, page views, and other user behaviors, while also supporting custom event tracking for business-critical actions.
This guide covers all installation methods for Heap across web, mobile, and server environments, including framework-specific integrations and best practices for production deployments.
Key Features
- Autocapture: Automatically tracks clicks, taps, form submissions, and page views without manual instrumentation
- Retroactive analysis: Define events after data collection to analyze historical user behavior
- Session replay: Visual playback of user sessions for debugging and UX optimization
- Identity management: Unify user behavior across devices and sessions
- Event visualizer: Point-and-click interface to define events without code changes
Deployment Considerations
Before installing Heap, evaluate these architectural decisions:
- Installation method: Tag manager, direct embed, npm package, or framework-specific integration
- Environment strategy: Separate App IDs for development, staging, and production
- Consent management: GDPR/CCPA compliance requirements and consent gating
- Autocapture scope: Which selectors to track, redact, or exclude
- Session replay: Whether to enable visual session recording
- Identity strategy: How to link anonymous and identified user sessions
Prerequisites
Account Setup
- Create a Heap account at heap.io or log into your existing organization
- Obtain your App ID from Account → Projects → Installation
- Create environment-specific projects:
- Development App ID for local testing
- Staging App ID for QA environments
- Production App ID for live traffic
- Configure project settings:
- Enable/disable session replay per environment
- Set data retention policies
- Configure IP blocklisting for internal traffic
- Define user privacy settings
Technical Requirements
- Web: Modern browsers (Chrome 90+, Firefox 88+, Safari 14+, Edge 90+)
- Mobile: iOS 12+ (Swift 5.0+) or Android 5.0+ (API level 21+)
- Server: Node.js 12+, Python 3.6+, Ruby 2.5+, Java 8+, or PHP 7.2+
- Package managers: npm 6+, yarn 1.22+, CocoaPods 1.10+, Gradle 6+
Security Considerations
- Store App IDs in environment variables, never hard-code in client-side code
- Use separate App IDs per environment to prevent test data pollution
- Configure Content Security Policy (CSP) to allow Heap domains
- Review and configure data redaction rules before going live
- Implement consent management for regulated regions
JavaScript Snippet Installation
Standard Installation
The simplest method is embedding the Heap snippet directly in your HTML <head>:
<script type="text/javascript">
window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.heapanalytics.com/js/heap-"+e+".js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a);for(var n=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["addEventProperties","addUserProperties","clearEventProperties","identify","resetIdentity","removeEventProperty","setEventProperties","track","unsetEventProperty"],o=0;o<p.length;o++)heap[p[o]]=n(p[o])};
heap.load("YOUR_APP_ID");
</script>
Placement: Insert this snippet as high in the <head> as possible, before other analytics tools, to ensure Heap captures early page interactions and attribution parameters.
Environment-specific App IDs: Use server-side templating to inject the correct App ID:
<!-- Example with environment variable -->
<script type="text/javascript">
window.heap=window.heap||[],heap.load=function(e,t){/* ... snippet code ... */};
heap.load("<%= ENV['HEAP_APP_ID'] %>");
</script>
Configuration Options
Pass configuration options as the second parameter to heap.load():
heap.load("YOUR_APP_ID", {
// Disable autocapture for manual-only tracking
disableTextCapture: false,
// Enable secure cookies for HTTPS-only sites
secureCookie: true,
// Capture iframe interactions (requires same-origin)
captureIframes: false,
// Disable session replay globally
disableReplayCapture: false,
// Custom beacon endpoint for proxying
endpoint: "https://your-proxy.example.com/heap",
// Selector-based redaction
redactSelectors: [
".sensitive-data",
"[data-sensitive]",
"input[type='password']"
],
// Redact all text content (capture structure only)
redactText: false
});
Consent Management Integration
Gate Heap initialization behind user consent for GDPR/CCPA compliance:
// Wait for consent before loading Heap
function initializeHeapWithConsent() {
// Check your consent management platform
if (hasAnalyticsConsent()) {
heap.load("YOUR_APP_ID", {
disableReplayCapture: !hasReplayConsent()
});
}
}
// Listen for consent changes
window.addEventListener('consentUpdate', function(event) {
if (event.detail.analytics && !window.heap.appid) {
heap.load("YOUR_APP_ID");
}
});
NPM Package Installation
For modern JavaScript projects using bundlers (Webpack, Rollup, Vite), install Heap via npm:
npm install heap-js
# or
yarn add heap-js
Basic Implementation
import heap from 'heap-js';
// Initialize Heap
heap.load('YOUR_APP_ID', {
secureCookie: true,
disableTextCapture: false
});
// Track custom events
heap.track('Purchase Completed', {
revenue: 49.99,
currency: 'USD',
productId: 'prod_123'
});
// Identify users
heap.identify('user_abc123');
// Add user properties
heap.addUserProperties({
plan: 'Premium',
signupDate: '2025-01-15',
accountType: 'Business'
});
Environment-Specific Configuration
// config/heap.js
const heapConfig = {
development: {
appId: process.env.HEAP_DEV_APP_ID,
config: {
disableReplayCapture: true,
endpoint: 'http://localhost:8080/heap-proxy'
}
},
staging: {
appId: process.env.HEAP_STAGING_APP_ID,
config: {
disableReplayCapture: false
}
},
production: {
appId: process.env.HEAP_PROD_APP_ID,
config: {
secureCookie: true,
disableReplayCapture: false
}
}
};
const env = process.env.NODE_ENV || 'development';
const { appId, config } = heapConfig[env];
heap.load(appId, config);
export default heap;
Google Tag Manager Deployment
GTM provides environment management and testing capabilities for Heap deployments.
Setup Steps
Create Custom HTML Tag:
- Tag Type: Custom HTML
- Tag Name: "Heap Analytics - Initialization"
Insert Heap Snippet:
<script type="text/javascript">
window.heap=window.heap||[],heap.load=function(e,t){/* ... full snippet ... */};
heap.load("{{Heap App ID}}", {
secureCookie: true,
redactSelectors: {{Heap Redact Selectors}}
});
</script>
Create GTM Variables:
- Variable Name:
Heap App ID - Variable Type: Lookup Table
- Input Variable:
{{Environment}} - Output:
dev→1234567890(dev App ID)staging→2345678901(staging App ID)production→3456789012(production App ID)
- Variable Name:
Configure Trigger:
- Trigger Type: Consent Initialization (if using consent mode)
- OR Trigger Type: Page View - DOM Ready
- Fire On: All Pages
Set Tag Firing Priority:
- Priority: 100 (higher than other analytics tags)
- This ensures Heap loads early to capture all interactions
Identity and Custom Event Tags
Create additional GTM tags for user identification:
Identify User Tag:
<script>
if (window.heap && {{User ID}}) {
heap.identify({{User ID}});
heap.addUserProperties({
email: {{User Email}},
name: {{User Name}},
plan: {{Subscription Plan}},
signupDate: {{Account Created Date}}
});
}
</script>
Trigger: Custom Event = user_login or Data Layer Event
Custom Event Tracking Tag:
<script>
if (window.heap) {
heap.track({{Event Name}}, {
category: {{Event Category}},
value: {{Event Value}},
properties: {{Event Properties}}
});
}
</script>
Trigger: Custom events mapped to your tracking plan
React Integration
Using the NPM Package
Install and configure Heap in your React application:
npm install heap-js
Initialize in App Root:
// src/App.js
import { useEffect } from 'react';
import heap from 'heap-js';
function App() {
useEffect(() => {
// Initialize Heap on app mount
if (process.env.REACT_APP_HEAP_APP_ID) {
heap.load(process.env.REACT_APP_HEAP_APP_ID, {
secureCookie: true,
disableTextCapture: false
});
}
}, []);
return (
<div className="App">
{/* Your app content */}
</div>
);
}
export default App;
Custom Hook for Heap
Create a reusable hook for Heap tracking:
// hooks/useHeap.js
import { useEffect, useCallback } from 'react';
import heap from 'heap-js';
export const useHeap = () => {
const trackEvent = useCallback((eventName, properties = {}) => {
if (window.heap) {
heap.track(eventName, properties);
}
}, []);
const identifyUser = useCallback((userId, properties = {}) => {
if (window.heap && userId) {
heap.identify(userId);
if (Object.keys(properties).length > 0) {
heap.addUserProperties(properties);
}
}
}, []);
const addUserProperties = useCallback((properties) => {
if (window.heap) {
heap.addUserProperties(properties);
}
}, []);
return { trackEvent, identifyUser, addUserProperties };
};
Usage in Components:
// components/Checkout.js
import { useHeap } from '../hooks/useHeap';
function Checkout() {
const { trackEvent } = useHeap();
const handlePurchase = (order) => {
trackEvent('Purchase Completed', {
revenue: order.total,
currency: 'USD',
items: order.items.length,
paymentMethod: order.paymentMethod
});
};
return (
<button => handlePurchase(orderData)}>
Complete Purchase
</button>
);
}
React Router Integration
Track page views in single-page applications:
// src/App.js
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import heap from 'heap-js';
function App() {
const location = useLocation();
useEffect(() => {
// Track virtual pageviews on route changes
if (window.heap) {
heap.track('Pageview', {
path: location.pathname,
search: location.search,
hash: location.hash
});
}
}, [location]);
return (
<Router>
{/* Your routes */}
</Router>
);
}
Vue.js Integration
Vue 3 Plugin
Create a Heap plugin for Vue 3:
// plugins/heap.js
import heap from 'heap-js';
export default {
install: (app, options) => {
// Initialize Heap
heap.load(options.appId, options.config || {});
// Add global properties
app.config.globalProperties.$heap = heap;
// Add track method
app.config.globalProperties.$trackEvent = (eventName, properties) => {
heap.track(eventName, properties);
};
// Add identify method
app.config.globalProperties.$identifyUser = (userId, properties) => {
heap.identify(userId);
if (properties) {
heap.addUserProperties(properties);
}
};
}
};
Register Plugin:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import heapPlugin from './plugins/heap';
const app = createApp(App);
app.use(heapPlugin, {
appId: import.meta.env.VITE_HEAP_APP_ID,
config: {
secureCookie: true,
disableTextCapture: false
}
});
app.mount('#app');
Usage in Components:
<template>
<button @click="trackPurchase">Complete Purchase</button>
</template>
<script>
export default {
methods: {
trackPurchase() {
this.$trackEvent('Purchase Completed', {
revenue: this.orderTotal,
currency: 'USD',
productId: this.product.id
});
}
}
};
</script>
Vue Router Integration
// router/index.js
import { createRouter } from 'vue-router';
import heap from 'heap-js';
const router = createRouter({
// ... routes
});
router.afterEach((to, from) => {
if (window.heap) {
heap.track('Pageview', {
path: to.path,
name: to.name,
params: to.params,
query: to.query
});
}
});
export default router;
Angular Integration
Service-Based Approach
Create a Heap service for Angular:
// services/heap.service.ts
import { Injectable } from '@angular/core';
import heap from 'heap-js';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class HeapService {
constructor() {
this.initialize();
}
private initialize(): void {
if (environment.heapAppId) {
heap.load(environment.heapAppId, {
secureCookie: environment.production,
disableTextCapture: false
});
}
}
track(eventName: string, properties?: Record<string, any>): void {
if (window.heap) {
heap.track(eventName, properties);
}
}
identify(userId: string, properties?: Record<string, any>): void {
if (window.heap && userId) {
heap.identify(userId);
if (properties) {
heap.addUserProperties(properties);
}
}
}
addUserProperties(properties: Record<string, any>): void {
if (window.heap) {
heap.addUserProperties(properties);
}
}
resetIdentity(): void {
if (window.heap) {
heap.resetIdentity();
}
}
}
Environment Configuration:
// environments/environment.prod.ts
export const environment = {
production: true,
heapAppId: 'YOUR_PROD_APP_ID'
};
// environments/environment.ts
export const environment = {
production: false,
heapAppId: 'YOUR_DEV_APP_ID'
};
Usage in Components:
// components/checkout/checkout.component.ts
import { Component } from '@angular/core';
import { HeapService } from '../../services/heap.service';
@Component({
selector: 'app-checkout',
templateUrl: './checkout.component.html'
})
export class CheckoutComponent {
constructor(private heap: HeapService) {}
completePurchase(order: any): void {
this.heap.track('Purchase Completed', {
revenue: order.total,
currency: 'USD',
items: order.items.length
});
}
}
Router Event Tracking
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { HeapService } from './services/heap.service';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private heap: HeapService
) {}
ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
this.heap.track('Pageview', {
path: event.urlAfterRedirects
});
});
}
}
Next.js Integration
App Router (Next.js 13+)
Create a Heap provider component:
// components/HeapProvider.tsx
'use client';
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import heap from 'heap-js';
export default function HeapProvider({
children
}: {
children: React.ReactNode
}) {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
// Initialize Heap
if (process.env.NEXT_PUBLIC_HEAP_APP_ID) {
heap.load(process.env.NEXT_PUBLIC_HEAP_APP_ID, {
secureCookie: true,
disableTextCapture: false
});
}
}, []);
useEffect(() => {
// Track page views on route changes
if (window.heap) {
heap.track('Pageview', {
path: pathname,
search: searchParams.toString()
});
}
}, [pathname, searchParams]);
return <>{children}</>;
}
Add to Root Layout:
// app/layout.tsx
import HeapProvider from '@/components/HeapProvider';
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<HeapProvider>
{children}
</HeapProvider>
</body>
</html>
);
}
Pages Router (Next.js 12 and earlier)
// pages/_app.tsx
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import heap from 'heap-js';
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
useEffect(() => {
// Initialize Heap
if (process.env.NEXT_PUBLIC_HEAP_APP_ID) {
heap.load(process.env.NEXT_PUBLIC_HEAP_APP_ID);
}
}, []);
useEffect(() => {
const handleRouteChange = (url: string) => {
if (window.heap) {
heap.track('Pageview', { path: url });
}
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
}
export default MyApp;
Mobile SDKs
iOS (Swift)
Installation via CocoaPods:
# Podfile
platform :ios, '12.0'
target 'YourApp' do
use_frameworks!
pod 'Heap', '~> 8.0'
end
pod install
Initialize in AppDelegate:
// AppDelegate.swift
import UIKit
import Heap
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
#if DEBUG
Heap.initialize("DEV_APP_ID")
#else
Heap.initialize("PROD_APP_ID")
#endif
Heap.setLogLevel(.info)
return true
}
}
Track Custom Events:
// Identify user
Heap.identify("user_123")
Heap.addUserProperties(["plan": "Premium", "signupDate": "2025-01-15"])
// Track events
Heap.track("Purchase Completed", withProperties: [
"revenue": 49.99,
"currency": "USD",
"productId": "prod_123"
])
Android (Kotlin)
Installation via Gradle:
// build.gradle (app level)
dependencies {
implementation 'com.heapanalytics.android:heap-android-client:3.+'
}
Initialize in Application Class:
// MainApplication.kt
import android.app.Application
import com.heapanalytics.android.Heap
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
val appId = if (BuildConfig.DEBUG) {
"DEV_APP_ID"
} else {
"PROD_APP_ID"
}
Heap.init(this, appId)
Heap.setLogLevel(Heap.LogLevel.INFO)
}
}
Track Custom Events:
// Identify user
Heap.identify("user_123")
Heap.addUserProperties(mapOf(
"plan" to "Premium",
"signupDate" to "2025-01-15"
))
// Track events
Heap.track("Purchase Completed", mapOf(
"revenue" to 49.99,
"currency" to "USD",
"productId" to "prod_123"
))
React Native
npm install @heap/react-native-heap
# iOS only:
cd ios && pod install && cd ..
Initialize:
// App.js
import Heap from '@heap/react-native-heap';
const App = () => {
useEffect(() => {
const appId = __DEV__ ? 'DEV_APP_ID' : 'PROD_APP_ID';
Heap.initialize(appId);
}, []);
return <YourApp />;
};
Server-Side Collection
Node.js
npm install heap-api
const Heap = require('heap-api');
const heap = new Heap('YOUR_APP_ID');
// Track server-side events
heap.track('Order Completed', 'user_123', {
revenue: 149.99,
currency: 'USD',
orderId: 'order_789',
items: 3
});
// Add user properties
heap.addUserProperties('user_123', {
plan: 'Enterprise',
mrr: 499,
companySize: '50-100'
});
Python
pip install heap-python
from heap import Heap
heap = Heap('YOUR_APP_ID')
# Track events
heap.track(
'user_123',
'Subscription Upgraded',
{
'previousPlan': 'Pro',
'newPlan': 'Enterprise',
'revenue': 299.99
}
)
# Add user properties
heap.add_user_properties('user_123', {
'plan': 'Enterprise',
'industry': 'Technology'
})
Verification Steps
1. Live Data Feed
After installation, verify Heap is collecting data:
- Navigate to Data → Live in Heap dashboard
- Perform test interactions on your site/app
- Confirm events appear in real-time feed within 30 seconds
- Verify event properties contain expected values
- Check that user identity persists across sessions
2. Session Replay Validation
If session replay is enabled:
- Navigate to Replay → Sessions in Heap dashboard
- Find your test session (filter by user ID or timeframe)
- Play back the session to verify visual recording quality
- Confirm sensitive fields are properly redacted
- Check console logs and network requests are captured
3. Identity Verification
Test user identification:
// Web test
heap.identify('test_user_' + Date.now());
heap.addUserProperties({
testProperty: 'verification_test',
timestamp: new Date().toISOString()
});
// Check in Heap dashboard:
// Data → Users → search for test_user_*
Verify:
- User appears in Users list
- Properties are attached correctly
- Identity persists across page reloads
- Anonymous and identified sessions are linked
4. Custom Event Validation
heap.track('Test Event', {
testProperty: 'value',
timestamp: Date.now(),
environment: 'testing'
});
Check:
- Event appears in Data → Events within 1 minute
- Properties are correctly typed (string, number, boolean)
- Event count increments with each test
5. Environment Separation
Verify App IDs are correctly segregated:
- Development events only appear in dev environment
- Production App ID receives live traffic
- No cross-contamination between environments
Troubleshooting
Events Not Appearing
Check browser console:
// Verify Heap is loaded
console.log(window.heap);
// Check App ID
console.log(window.heap.appid);
// Verify initialization
console.log(window.heap.config);
Common issues:
- Ad blockers: Heap may be blocked by browser extensions
- Solution: Test in incognito mode or whitelist Heap domains
- CSP violations: Content Security Policy blocking Heap script
- Solution: Add
cdn.heapanalytics.comto CSP directives
- Solution: Add
- Incorrect App ID: Wrong environment ID configured
- Solution: Verify App ID matches environment in Heap dashboard
- Async timing: Page loads before Heap initialization
- Solution: Use
heap.load()callback or checkwindow.heap.loaded
- Solution: Use
Identity Not Persisting
Check cookies:
// Verify Heap identity cookie
document.cookie.split(';').filter(c => c.includes('_hp2_id'));
Common issues:
- Cookie restrictions: Browser blocking third-party cookies
- Solution: Enable
secureCookie: trueand serve over HTTPS
- Solution: Enable
- Domain mismatch: Subdomain cookie scope issues
- Solution: Configure cookie domain in Heap settings
- Identity timing: Calling
identify()before Heap loads- Solution: Wrap in
heap.load()callback or check initialization
- Solution: Wrap in
Session Replay Not Recording
Verify replay is enabled:
console.log(!window.heap.config.disableReplayCapture);
Common issues:
- Disabled in project: Replay not enabled in Heap dashboard
- Solution: Enable in Project Settings → Session Replay
- Privacy mode: User opted out of recording
- Solution: Check consent management integration
- Iframe content: Cross-origin iframes not captured
- Solution: Enable
captureIframes: truefor same-origin frames
- Solution: Enable
- Canvas/WebGL: Complex graphics may not render
- Solution: Heap captures DOM only, not rendered canvas content
Performance Impact
Monitor performance:
// Check Heap script load time
performance.getEntriesByName('https://cdn.heapanalytics.com/js/heap-*.js');
// Monitor event queue size
console.log(window.heap.length);
Optimization strategies:
- Defer non-critical events: Batch track calls during idle time
- Reduce autocapture scope: Configure
disableTextCaptureor selector exclusions - Lazy load replay: Disable replay on mobile or low-end devices
- CDN proximity: Verify CDN edge servers are geographically close
Data Redaction Issues
Test redaction rules:
// Check if selectors are redacted
heap.load('YOUR_APP_ID', {
redactSelectors: ['.sensitive', '[data-private]']
});
// Verify in session replay and autocapture data
Common issues:
- Dynamic content: Elements added after page load not redacted
- Solution: Use broader CSS selectors or
data-heap-redact-textattributes
- Solution: Use broader CSS selectors or
- Form inputs: Sensitive form fields captured
- Solution: Add
type="password"orautocomplete="off"attributes
- Solution: Add
- PII in URLs: Query parameters containing personal data
- Solution: Configure URL parameter redaction in Heap settings
Security Best Practices
1. Environment Segregation
// Never hard-code App IDs
// Bad
heap.load('1234567890');
// Good
heap.load(process.env.HEAP_APP_ID);
2. Data Minimization
Configure redaction rules to exclude PII:
heap.load('YOUR_APP_ID', {
redactSelectors: [
'input[type="email"]',
'input[type="tel"]',
'input[type="ssn"]',
'.pii-data',
'[data-sensitive]'
],
redactText: false // Only redact specified selectors
});
3. Consent Management
Implement proper consent gating:
// Check consent before initializing
function initializeHeapIfConsented() {
const consent = getCookieConsent(); // Your CMP
if (consent.analytics) {
heap.load('YOUR_APP_ID', {
disableReplayCapture: !consent.replay
});
}
}
// Listen for consent changes
window.addEventListener('consentUpdate', (event) => {
if (event.detail.analytics && !window.heap.appid) {
initializeHeapIfConsented();
}
});
4. CSP Configuration
Add Heap domains to Content Security Policy:
Content-Security-Policy:
script-src 'self' https://cdn.heapanalytics.com;
connect-src 'self' https://heapanalytics.com https://*.heapanalytics.com;
img-src 'self' https://heapanalytics.com;
5. Secure Cookie Configuration
heap.load('YOUR_APP_ID', {
secureCookie: true, // HTTPS only
sameSite: 'Lax' // CSRF protection
});
Performance Optimization
1. Async Loading
Heap loads asynchronously by default, but verify:
// Check async attribute
const heapScript = document.querySelector('script[src*="heapanalytics.com"]');
console.log(heapScript.async); // Should be true
2. Event Batching
For high-frequency events, implement batching:
let eventQueue = [];
const BATCH_SIZE = 10;
const BATCH_INTERVAL = 5000;
function queueEvent(eventName, properties) {
eventQueue.push({ eventName, properties });
if (eventQueue.length >= BATCH_SIZE) {
flushEvents();
}
}
function flushEvents() {
eventQueue.forEach(event => {
heap.track(event.eventName, event.properties);
});
eventQueue = [];
}
// Flush every 5 seconds
setInterval(flushEvents, BATCH_INTERVAL);
// Flush on page unload
window.addEventListener('beforeunload', flushEvents);
3. Selective Autocapture
Reduce autocapture overhead:
heap.load('YOUR_APP_ID', {
// Disable text capture for performance
disableTextCapture: true,
// Disable iframe tracking
captureIframes: false,
// Manual pageview tracking only
trackPageview: false
});
// Manually track important interactions
document.querySelectorAll('.cta-button').forEach(button => {
button.addEventListener('click', () => {
heap.track('CTA Clicked', {
buttonText: button.textContent,
location: button.dataset.location
});
});
});
4. Lazy Load Session Replay
Conditionally enable replay based on user segment:
const shouldEnableReplay = () => {
// Disable on mobile for performance
if (/Mobi|Android/i.test(navigator.userAgent)) {
return false;
}
// Sample 10% of sessions
if (Math.random() > 0.1) {
return false;
}
return true;
};
heap.load('YOUR_APP_ID', {
disableReplayCapture: !shouldEnableReplay()
});
Advanced Configuration
Cross-Domain Tracking
Track users across multiple domains:
// Domain A (example.com)
heap.load('YOUR_APP_ID', {
crossDomainLinking: true,
crossDomainLinkerParameter: '_heap_id'
});
// Domain B (shop.example.com)
heap.load('YOUR_APP_ID', {
crossDomainLinking: true,
crossDomainLinkerParameter: '_heap_id'
});
// Add linker parameter to cross-domain links
document.querySelectorAll('a[href*="shop.example.com"]').forEach(link => {
const url = new URL(link.href);
url.searchParams.set('_heap_id', window.heap.identity);
link.href = url.toString();
});
Custom Endpoints (Proxying)
Route Heap requests through your domain to avoid ad blockers:
heap.load('YOUR_APP_ID', {
endpoint: 'https://analytics.yourdomain.com/heap'
});
Nginx proxy configuration:
location /heap {
proxy_pass https://heapanalytics.com;
proxy_set_header Host heapanalytics.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_ssl_server_name on;
}
Event Property Enrichment
Add global properties to all events:
// After initialization
heap.addEventProperties({
environment: 'production',
appVersion: '2.5.0',
buildNumber: '12345',
releaseDate: '2025-01-15'
});
// Remove event properties
heap.removeEventProperty('buildNumber');
// Clear all event properties
heap.clearEventProperties();
Conditional Identity
Link sessions only for authenticated users:
// Anonymous browsing
heap.load('YOUR_APP_ID');
// User logs in
function onUserLogin(user) {
heap.identify(user.id);
heap.addUserProperties({
email: user.email,
name: user.name,
plan: user.subscription.plan,
signupDate: user.createdAt
});
}
// User logs out
function onUserLogout() {
heap.resetIdentity(); // Start new anonymous session
}
Configuration Recommendations
Autocapture vs. Manual Events: Rely on autocapture for UI interactions (clicks, form submissions, page views) — it works retroactively, meaning you can define events after the fact without redeploying code. Use manual heap.track() calls only for business logic events that aren't tied to DOM interactions (API responses, background processes, calculated values like revenue).
Session Replay: Enable replay selectively — start with 10% sampling (heap.setEventProperties({ replay_sample: Math.random() < 0.1 })) and increase as needed. Replay consumes significant quota. Disable replay in staging environments. Ensure your privacy policy covers session recording.
PII Redaction: Heap autocapture can inadvertently capture text content from the page. Use heap.addEventProperties cautiously and configure CSS selectors for redaction: add heap-ignore class to elements containing sensitive data, or use heap-redact-text to mask text while preserving click tracking.
Data Retention: Heap retains data for 12 months by default (configurable on enterprise plans). For compliance, configure shorter retention in Settings → Data Governance. Heap provides GDPR deletion APIs for individual user data removal requests.
Data Warehouse Export: Connect Heap to your warehouse (BigQuery, Snowflake, Redshift) via Settings → Integrations → Data Warehouse. Exports run daily. Use warehouse data for custom attribution models and joining Heap behavioral data with backend transaction data.