# How to Vibe Code Your Own Heap (and Stop Paying for It)

> Better Insights. Faster.

- Site: https://heap.io
- Category: Product Analytics
- Verdict: **Serious undertaking** (35/100 vibecodeable)
- Estimated effort: 6+ weeks of intensive development and data pipeline tuning

## Verdict

You can build a functional personal-use analytics dashboard with a custom tracking script, but achieving true retroactive autocapture at scale is a massive engineering feat.

Heap's core magic is twofold: an invisible autocapture client script that records every DOM interaction without manual tracking calls, and a columnar data engine capable of computing arbitrary funnels and journeys retroactively. While an AI agent can scaffold a Next.js dashboard, a ClickHouse instance, and a basic MutationObserver snippet in a few weeks, handling event deduplication, high-concurrency ingestion buffering, and retroactive querying will test the limits of solo vibecoding.

### What you can't replicate

- Enterprise-grade multi-tenant compliance (SOC 2, ISO 27001)
- High-throughput distributed ingestion pipelines handling billions of daily events
- The massive historical dataset required for industry benchmarks and AI training models

## What it does

Digital insights and product analytics platform that automatically captures user interactions across web and mobile applications.

### Core features

- Lightweight autocapture JavaScript tracking snippet
- Real-time event ingestion pipeline and buffer
- Analytical data store (ClickHouse / columnar storage)
- Retroactive event definition and visual labeling engine
- Core analytics charts (Funnels, Retention, Journeys)
- Natural language analytics assistant (Sense AI)
- Session replay and DOM mutation recorder
- User cohort segmentation and dashboards

## The business

### Pricing

- Free: Free
- Growth: Custom / Session-based
- Pro: Custom / Session-based
- Premier: Custom / Session-based

### Funding

$216M raised.
- Series A (August 2013)
- Series B (May 2017)
- Series C (July 2019)
- Series D (December 2021)
Investors: Goldman Sachs Asset Management, Maverick Ventures, New Enterprise Associates, Menlo Ventures, Initialized Capital

Founded 2013.
Team size: 100-150.

## The hard parts

- Building a non-blocking, microscopic client autocapture script that records clicks, inputs, and page views without breaking target apps
- Handling massive high-throughput event write streams and indexing them for instant analytical aggregation
- Designing a retroactive query engine that computes arbitrary user-defined events over historical raw event logs
- Capturing high-fidelity DOM state changes and serializing user sessions for replay without tanking client browser performance

## How to vibe code Heap

### Prerequisites

- Node.js (free): Required for running the Next.js frontend and ingestion API worker.
- GitHub (free): Source code repository and CI/CD deployment connection.
- Anthropic API (Pay-as-you-go (~$10-20/mo)): Powers the natural language query assistant (Sense AI).

### Recommended AI tools

- Claude Code: Best-in-class agentic CLI for scaffolding multi-file tracking SDKs, API ingestion routes, and analytical database queries.
- Cursor: Essential for iterative UI development on the analytics dashboard components, charts, and funnel builders.

### Stack

- Frontend: Next.js with Tailwind CSS, Recharts / D3.js, and shadcn/ui
- Backend: Next.js API Routes / Edge Functions for event ingestion ingestion endpoints
- Database: ClickHouse Cloud for high-performance event analytics storage; Neon for user accounts and metadata
- Auth: better-auth
- Payments: None (Personal-use clone)
- Other: Clickhouse JS client, Zod for payload validation, rrweb for session replay capture

### Hosting

- Vercel (Hosting the Next.js analytics dashboard and ingestion API endpoints): $0-20/mo
- ClickHouse (Managed columnar event storage for high-throughput behavioral analytics): $0-25/mo
- Neon (Relational storage for user accounts, projects, and event definitions): $0/mo

### Build guide

1. **Project Scaffolding & Database Schema Setup** — Initialize the Next.js project with Tailwind CSS, shadcn/ui, and configure connections to Neon (for users/projects) and ClickHouse (for raw event ingestion).

```
Create a new Next.js project with TypeScript, Tailwind CSS, and App Router. Set up Drizzle ORM configured with a Neon Postgres connection for managing users, organizations, projects, and custom event definition metadata. Create a ClickHouse client initialization utility for high-throughput behavioral event tables with columns for event_id, project_id, session_id, user_id, event_type, target_selector, url, timestamp, and metadata (JSON). Ensure proper TypeScript types for all database models and provide an initialization migration script.
```

2. **Build the Client-Side Autocapture SDK** — Develop a lightweight vanilla JavaScript snippet that attaches event listeners to capture clicks, input changes, and page views, batching and flushing events via Beacon API.

```
Build a standalone client-side tracking script (written in TypeScript, bundled to a lightweight JS snippet) that initializes with a project API key. The script must automatically capture page views (including SPA history changes), click events with DOM path selectors and text content, form input changes (excluding masked sensitive inputs like passwords), and session lifecycles (generating unique session IDs with a 30-minute inactivity timeout). Implement a batching queue that flushes events to our ingest endpoint using navigator.sendBeacon or fetch with keepalive. Handle offline retries and ensure zero impact on host application performance.
```

3. **High-Throughput Ingestion API** — Implement a high-performance Next.js API route to receive, validate, and bulk insert event payloads into ClickHouse.

```
Create a robust ingestion API endpoint at /api/v1/track that accepts batch event payloads from our client SDK. Validate incoming requests using Zod schemas, verify the project API key against the Neon database cache, sanitize payload data to prevent injection, and efficiently insert the events into the ClickHouse event log table. Implement rate limiting and CORS headers so third-party web apps can transmit events seamlessly. Add basic error logging and retry mechanisms for database write failures.
```

4. **Core Analytics Query Engine (Funnels, Retention, Journeys)** — Build SQL aggregation queries and API endpoints to compute funnels, user retention cohorts, and event frequency charts from ClickHouse data.

```
Build analytical API endpoints that query ClickHouse to compute product metrics. Specifically implement: (1) Funnel analysis calculating conversion rates across ordered sequences of custom events over user sessions; (2) Retention cohorts tracking percentage of users returning on days N after their initial activation event; (3) Event frequency and breakdown charts grouped by user segments or properties. Ensure queries are optimized with proper ClickHouse projection and index strategies for fast response times over large event volumes.
```

5. **Visual Event Labeling & Retroactive Definition Engine** — Create an administrative interface for mapping raw autocaptured click selectors to named business events (e.g., 'Clicked Signup Button').

```
Build a visual event governance dashboard in Next.js where users can define named custom events retroactively. A user should be able to specify filter criteria (e.g., event_type = 'click' AND target_selector LIKE '%signup-btn%') and assign a friendly display name. Store these event definitions in Neon. When users query analytics charts, dynamically map these saved definitions to underlying ClickHouse SQL queries so historical autocaptured data immediately reflects the new event rule without requiring code changes.
```

6. **Natural Language Query Assistant (Sense AI)** — Integrate the Anthropic API to parse natural language questions into analytical queries and render corresponding chart components.

```
Implement an AI assistant chat interface ('Sense AI') powered by the Anthropic API. The backend route should receive natural language user prompts (e.g., 'Show me weekly conversion rates for the onboarding funnel') along with the project's schema and saved event definitions. Construct a prompt instructing Claude to return a structured JSON object defining the exact analytical query parameters (chart type, steps, date ranges). On the frontend, parse this JSON response to dynamically render the corresponding Recharts visualization and summarize key insights for the user.
```

7. **Session Replay Integration** — Integrate rrweb or a DOM mutation recorder into the tracking script and build a video-like player interface in the dashboard.

```
Integrate rrweb into the client tracking snippet to record DOM mutations, mouse movements, and console logs efficiently. Stream session snapshots and incremental mutation chunks to our backend storage (or ClickHouse binary columns). Build a dashboard player view using the rrweb player component that lets users select a recorded session ID, playback user interactions chronologically, skip idle periods, and inspect network logs or errors tied to that specific session.
```

### Cost vs paying

**Starting costs (one-time):**

- Custom Domain: $12 one-time
- AI Coding Credits: $20
- Total: ~$32 one-time

**Ongoing costs (monthly):**

- Vercel Pro / Edge Hosting: $20/mo
- ClickHouse Cloud / Neon DB: $25/mo
- Total: ~$45/mo

- Paying for the SaaS instead: $200 - $1,000+/mo (Tiered volume pricing)
- Build time: 80-120 hours
- AI tool credits: $20 (Claude Pro / Cursor)
- Break-even: Self-hosted alternative is built for learning and personal analytics control rather than direct financial ROI against low-tier SaaS plans.

## Sources

- [Heap Home Page](https://heap.io)
- [Heap Pricing Page](https://heap.io/pricing)
- [Contentsquare Acquisition Press Release](https://contentsquare.com)
- [Tracxn Heap Profile](https://tracxn.com/d/companies/heap)