---
title: "How to add heatmaps to your app with Codex CLI"
description: "Use Codex CLI to add heatmaps, preserve replay privacy, separate report URLs, and verify capture in Amplitude."
canonical: "https://amplitude.com/build/codex-cli-heatmaps"
---

# How to add heatmaps to your app with Codex CLI

Use Codex CLI to add heatmaps, preserve replay privacy, separate report URLs, and verify capture in Amplitude.

Source: https://amplitude.com/build/codex-cli-heatmaps

---

# How to add heatmaps to your app with Codex CLI

Use Codex CLI to enable replay capture for a report app, give weekly and monthly reports distinct URLs, and configure a heatmap. Review the generated changes against a complete browser example and verify the result in Amplitude.

- Codex CLI
- Vite
- Unified SDK 1.1.43
- 25 min

Chris Tam · Last updated 9 November 2026

I use Codex CLI in the app repository to add capture and test report navigation. Amplitude [heatmaps](https://amplitude.com/heatmaps) group the interactions captured through session replay, so I give each report view a distinct path.

In this tutorial, you'll prompt Codex CLI, review replay capture and privacy, separate report URLs, and configure a heatmap that fills in as eligible traffic arrives.

A report app with separate weekly and monthly URLs, one browser SDK initialization, replay privacy controls, and a heatmap configured for a report URL. A short test confirms capture and navigation; an overlay also needs enough processed replay data.

## Prerequisites

- Codex CLI installed and signed in, with a local web app repository you can edit. Launch it from the project directory and review the permissions and usage available to your account.
- Node.js 22.12 or later and Corepack with pnpm 10.33.2. The example pins Vite 8.3.4 and `@amplitude/unified` 1.1.43; it doesn't require another Build tutorial.
- A development Amplitude project and its public client API key from Settings > Projects > your project > General. Confirm its US or EU data center. Check that the project has access to the product and capacity for your test.

Heatmaps are available on Plus, Growth, and Enterprise with session replay access. [Compare plans](https://amplitude.com/pricing) and [sign up for Amplitude](https://app.amplitude.com/signup). Confirm that your project has heatmaps access; an Admin or Manager can enable capture. Use a separate development project for synthetic checks.

## 1. Open the project and connect context

I open Codex CLI from the app's repository so it can inspect the actual entry point, router and instructions. For an empty folder, create the standalone Vite files in step 4. For an existing app, preserve its authentication, consent, routes and enabled products.

Terminal

```sh
codex
```

Inspection prompt

```text
Inspect this repository's framework, browser entry point, existing Amplitude client, consent, authentication, package manager and AGENTS.md. Read relevant nested project instructions too. Identify the existing development and build commands. Explain the proposed files and checks before modifying anything.
```

The complete standalone reference below runs locally with Vite. If the app uses React or server rendering, merge the same SDK behavior into that setup. Load browser-only SDK code from a client lifecycle or click handler, and preserve a single initialization promise across remounts and repeated actions.

**MCP.** An optional [Amplitude MCP connection](https://amplitude.com/docs/amplitude-ai/amplitude-mcp) can supply the project's existing taxonomy. Review its account permissions before connecting. MCP access and the browser application's client API key are separate; this SDK integration works without an MCP connection.

## 2. Give the agent a precise implementation prompt

I ask Codex CLI for a plan before changing files. Use the planning-only instruction below, review the proposed files and tests, then explicitly ask it to implement that plan.

Implementation prompt

```text
Planning only: inspect and read the sources, then show the proposed files and tests. Do not modify files yet; stop and wait for my approval to implement.

Work in this local repository and first inspect its app entry point, existing Amplitude initialization, consent flow, authentication, package manager, root AGENTS.md and existing project instructions. Read the current official references at https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/reference and https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/instrument-and-configure and https://amplitude.com/docs/sdks/session-replay/session-replay-plugin. Report the source URLs. Read the full English source for each cited Amplitude page; its Markdown endpoint is https://amplitude.com/docs/api/content/ followed by the path after /docs/. Follow relevant links to the underlying Browser SDK 2 reference when checking nested analytics options. Use complete source text rather than a search or fetch summary to resolve option names and defaults. Use these SDK docs rather than another Build tutorial to resolve SDK claims. Before changing code, describe the files you will touch and any conflicting existing setup.

Read the complete reference app at https://github.com/amplitude/ampli-examples/tree/ffac5f46bc32da3e3da20474708d974c70cd0eaa/browser/coding-tools/heatmaps. Fetch main.js directly from https://raw.githubusercontent.com/amplitude/ampli-examples/ffac5f46bc32da3e3da20474708d974c70cd0eaa/browser/coding-tools/heatmaps/main.js and read the sibling package.json, index.html, .env.example, .gitignore, pnpm-workspace.yaml, pnpm-lock.yaml and README.md. Preserve the repository owner amplitude. Use this Vite example as the SDK behavior reference and implement the same experience in this repository. Preserve its actual framework, scaffold, routes and package manager. Do not replace an existing app scaffold, backend, or router with this standalone Vite reference. Dynamically import browser-only SDK code from a client lifecycle or click handler so SSR never runs it. Keep a single initialization promise outside component render and guard repeated clicks, remounts and StrictMode. Show the full affected framework files for review. If you cannot read the reference, ask me to paste its files before implementing it. Give weekly and monthly reports distinct path URLs, preserving the existing router. A cosmetic tab that leaves the same URL merges its states in one map. Heatmaps use replay interactions, not click autocapture. For the isolated development demo only: Use @amplitude/unified 1.1.43 and initAll once after Start demo. Set top-level serverZone. Enable session events, set replay sampleRate to 1 for the development test, and skip engagement. Mask #sensitive and block #excluded in sessionReplay.privacyConfig. Keep the input masked. Set the synthetic user build-web-heatmaps-demo after initialization. Track Report Exported only from the export action. Keep replay active during the capture check. Preserve consent and privacy selectors when changing routes. Never treat the replay ID or an upload response as proof of correct processed masking.

In an existing app, use its existing analytics client, confirmed user identity, consent lifecycle, and enabled products. Do not copy the demo synthetic IDs or its sample/skip choices into that client. If the existing installation is not Unified, propose a documented compatible integration before changing initialization; never add a parallel client. Preserve routes, authentication, replay privacy, consent and other product setup. Do not replace whole shared files or reset identity while authentication is anonymous or loading. Read only public client configuration through VITE_ variables; never use server or admin credentials. Keep private credentials in the backend environment. Anything VITE_ is exposed in the browser bundle. Restart Vite after configuration changes and set production build-time values separately. Preserve the existing development server, deployment configuration and host validation. In the standalone local reference, keep .env.local ignored and retain the pnpm 10.33.2 integrity pin, minimum pnpm 10.21.0, release-age/trust settings and frozen lockfile. Preserve this project's existing package manager and lockfile. Report what was built, what was tested locally, and which service-side outcomes remain unverified. Stop the affected claim if current docs disagree; record both sources rather than guessing.
```

**MCP.** Ask the connected agent to inspect the project's existing event names before adding `Report Exported`. If your taxonomy already defines this action, use its established name consistently in the app and product configuration.

## 3. Review the proposed changes

Inspect the diff before accepting the implementation. I check the initialization and privacy paths before the visible UI, because a working button doesn't prove the integration is configured correctly.

Implementation prompt

```text
List every changed and new file. Show where the SDK is loaded only in the browser, how repeated initialization is prevented, where public configuration is read, and which existing authentication, consent and product settings are preserved. Run the project's existing build and test scripts. Report local checks separately from live Amplitude outcomes.
```

Review every changed and new file, including untracked files. I use these commands to inspect tracked changes and list new files before opening them.

Terminal

```sh
git status --short
git diff --stat
git diff
```

Confirm the agent uses `initAll`, sets `serverZone` at the top level, initializes once per page load, and preserves the existing client if the app already has one. In the local reference, check that `.env.local` is ignored. Vite embeds VITE\_ values in the browser bundle. Use only the public project API key there; keep server, admin, provider and secret credentials in the backend environment.

The complete example uses a fixed synthetic identity. In an existing app, connect your confirmed application identity and consent lifecycle. Don't overwrite your login handler, navigation, or another product's instrumentation with this demo.

## 4. Check the complete reference implementation

These are complete files for the standalone local browser reference. For an existing app, Codex CLI merges this behavior without replacing routes, its entry point or deployment setup. Compare the relevant imports, handlers, configuration and DOM targets with the agent's result.

The [Unified SDK installation guide](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/get-started) supplies the SDK setup. This example pins 1.1.43 for reproducible builds. The [current API reference](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/reference) describes the supported methods; newer releases can add options beyond this pinned example. Its initialization returns a plain promise, so the code awaits `initAll` directly.

package.json

```json
{
  "name": "amplitude-build-session-replay",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1"
  },
  "dependencies": {
    "@amplitude/unified": "1.1.43"
  },
  "devDependencies": {
    "vite": "8.3.4"
  }
```

pnpm-workspace.yaml

```yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
```

.gitignore

```text
node_modules/
dist/
.env.local
.env.qa
```

.env.example

```text
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
```

index.html

```html
<!doctype html>
<html lang="en">
  <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Usage report demo</title></head>
  <body>
    <main>
    <nav><a href="/reports/weekly">Weekly report</a> <a href="/reports/monthly">Monthly report</a></nav>
    <p id="report-route"></p>
      <h1>Usage report</h1>
      <p id="report-summary">84 actions in the past 7 days.</p>
      <button id="start">Start demo</button>
      <button id="export-report">Export report</button>
      <p>Local exports: <span id="exports">0</span></p>
      <p id="sensitive" class="amp-mask">SYNTHETIC PRIVATE LABEL</p>
    <label>Test note <input value="SYNTHETIC INPUT ONLY"></label>
    <section id="excluded" class="amp-block">SYNTHETIC EXCLUDED PANEL</section>
    <button id="pause" disabled>Pause recording</button>
      <p id="status" role="status">Demo stopped. Use synthetic data only.</p>
    </main>
    <script type="module" src="/main.js"></script>
  </body>
</html>
```

main.js

```javascript
import * as amplitude from "@amplitude/unified";

document.querySelector("#report-route").textContent = location.pathname === "/reports/monthly" ? "Monthly report" : "Weekly report";
document.querySelector("#report-summary").textContent = location.pathname === "/reports/monthly" ? "320 actions in the past 30 days." : "84 actions in the past 7 days.";
const apiKey = (import.meta.env.VITE_AMPLITUDE_API_KEY || "").trim();
const zone = (import.meta.env.VITE_AMPLITUDE_SERVER_ZONE || "US").trim();
const status = document.querySelector("#status");
const startButton = document.querySelector("#start");
const exportButton = document.querySelector("#export-report");
let started = false;
let starting;
let exports = 0;

exportButton.addEventListener("click", () => {
  exports += 1;
  document.querySelector("#exports").textContent = String(exports);
  if (started) amplitude.track("Report Exported", { report_period: location.pathname === "/reports/monthly" ? "30d" : "7d" });
});

startButton.addEventListener("click", () => {
  if (starting) return;
  if (!apiKey || !["US", "EU"].includes(zone)) {
    status.textContent = "Add the development configuration and restart Vite. Local export still works.";
    return;
  }
  startButton.disabled = true;
  starting = start().catch(() => {
    status.textContent = "Setup failed. Check configuration and connectivity, then reload.";
  });

async function start() {
  await amplitude.initAll(apiKey, {
    serverZone: zone,
    analytics: { autocapture: { sessions: true } },
    sessionReplay: {
      sampleRate: 1,
      privacyConfig: { defaultMaskLevel: "medium", maskSelector: ["#sensitive"], blockSelector: ["#excluded"] },
    },
    engagement: { skip: true },
  });
  amplitude.setUserId("build-web-heatmaps-demo");
  started = true;
  document.querySelector("#pause").disabled = false;
  status.textContent = `Replay requested; device ${amplitude.getDeviceId()}. Verify the processed recording.`;
}

document.querySelector("#pause").addEventListener("click", () => {
  amplitude.sessionReplay()?.stop();
  status.textContent = "Recording paused; analytics remains active.";
});
```

For this local reference, Vite's default host checks remain enabled and the server listens on loopback. For a hosted preview, use its documented deployment setup and allow only the intended trusted host.

Install from the checked-in manifest. Commit the generated lockfile, and use a frozen install in repeatable builds.

Terminal

```sh
corepack enable
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local
```

Fill in `.env.local` with the development configuration. The client key is public and limited to ingestion, but keeping it in local configuration avoids tying shared source to one project. See [Vite's environment-variable reference](https://vite.dev/guide/env-and-mode) for rebuild and browser-exposure behavior.

## 5. Configure capture and create the map

In Amplitude, open **Settings > Organizational Settings > Session Replay Settings**. Have an Admin or Manager enable session capture and heatmap capture for the development project. Check its sampling configuration and remaining replay capacity. A remote project sampling value can change what gets recorded; requesting `sampleRate: 1` locally does not bypass project controls.

Implementation prompt

```text
Development check:
- Confirm the correct project and data center.
- Enable session capture and heatmap capture only in the intended development project.
- Record synthetic interactions with sensitive text masked and excluded content blocked.
- Give weekly and monthly reports distinct paths in the app's existing router.
- Preserve the same Amplitude identity for replay and analytics.
```

Open **Heatmaps > + New Heatmap**, choose a map type, and use **Exact match** for the deployed weekly report URL. Start without a segment filter. Use a stable deployed or accessible preview URL; use the actual application page URL. Then check the monthly path separately.

Heatmaps need Session Replay Browser SDK Plugin 1.7.0 or later, or Standalone SDK 1.14.0 or later. Unified manages device ID alignment automatically. Read the installed replay version in Instrumentation Explorer's replay debug panel.

Heatmaps appear after roughly 500 replay clicks on each of at least 10 pages. These are approximate site-wide data requirements, not a promise that this two-page demo produces an overlay immediately. Confirm capture first and let eligible traffic accumulate; don't generate thousands of fake clicks to simulate a production result.

Choose a background from the same screen-width bucket as the interactions. If it looks wrong, use **Change Screenshot > From a Replay**. The buckets are greater than 1440px, 900 to 1440px, 500 to 899px, and less than 500px.

## 6. Run the report

Start Vite from the directory containing the reference files and open the local URL it prints. Export once before starting the SDK to confirm the report works without analytics configuration. Then choose Start demo once and perform the product check below.

Terminal

```sh
pnpm dev
```

After the development check, stop the server and verify the production build. Restart Vite after changing environment configuration.

Terminal

```sh
pnpm install --frozen-lockfile
pnpm build
```

## Verify it worked

1. Open `/reports/weekly`, export a synthetic report, then follow Monthly report. Confirm the address changes to `/reports/monthly`, including on a direct load. For a framework app, test both link navigation and direct route loads with its actual router.
2. Use Instrumentation Explorer to inspect the SDK version, device ID, replay ID, and capture settings. Read event contents there rather than a compressed Network request body.
3. Inspect a processed recording. Confirm the report navigation and export appear, private text is masked, and excluded contents are absent. A successful upload alone doesn't establish those privacy outcomes.
4. In Heatmaps, check the app's actual URL, date range, capture toggles, and sampling configuration. If the site has enough processed data, confirm the map and background share a screen-width bucket and the expected clicks appear.
5. Add segment or cohort filters only after the unsegmented map works. Empty segmented results can indicate mismatched device IDs or a filter without matching users.

Record capture, route behavior, and a populated overlay as separate outcomes. A local build or a short two-page session cannot prove that the data thresholds have been met.

## Troubleshooting

**The local page is blank.** Run pnpm dev from the reference directory and open the printed address. Check browser errors and the root script path. In a hosted app, keep the actual framework server and a narrow trusted-host allowlist.

**The map is blank.** Check capture toggles, processed replay data, date and URL filters, sampling, and the approximate site-wide data requirements. A working replay is necessary but doesn't establish a populated map.

**Weekly and monthly clicks overlap.** Keep each view at its own path using the existing router. Local state changes that share a URL merge into one map. Don't rely on query parameters to separate these views.

**Only segment filters are empty.** Confirm replay and analytics use the same device ID and, for signed-in users, the same user ID. Keep the existing Unified client rather than adding a separate initializer.

**The background looks wrong.** Use Change Screenshot > From a Replay and match the background to the data's screen-width bucket. Preserve masking because the background comes from replay capture.

**The hosted app fails during server rendering.** Have Codex CLI dynamically load the browser SDK from a client lifecycle or user action. Preserve one initialization promise and test direct route loads.

**The configuration guard stays visible.** Fill the ignored .env.local and restart Vite. VITE\_ values are public browser configuration; changing them after the production bundle is built requires a rebuild.

## FAQ

### Which Amplitude key goes in the browser app?

The browser app uses a public project API key. An MCP connection authenticates separately. Keep server deployment keys, admin tokens, and secret keys out of browser configuration and committed source.

### Can I use this in an existing app?

Yes. Have the agent merge the behavior into the existing browser entry point and client. Preserve authentication, consent, and routing. The standalone reference uses Vite. Keep the existing app scaffold and router. If it renders on a server, load browser-only SDK code dynamically from a client lifecycle or user action, and test direct route loads.

### Does a successful build prove the product works?

No. A build checks that the browser app can be bundled. The Verify section separately checks the rendered experience, processed activity, and the product result. Record which checks you performed before broadening the audience.

### Will the agent make the same changes every time?

Treat its output as a change to review. Keep the explicit prompt, pinned reference, and repository rules, then compare its diff with the required behavior. An agent can propose a different implementation without establishing that its SDK calls or product settings are correct.

## Full code reference

Step 4 contains the complete heatmaps reference. [Download the exact example and lockfile](https://github.com/amplitude/ampli-examples/tree/ffac5f46bc32da3e3da20474708d974c70cd0eaa/browser/coding-tools/heatmaps). The public source includes both report routes and replay privacy controls. Its optional .replit and hosted Vite configuration are for Replit; the local version here uses the manifest scripts and default Vite configuration. Compare SDK behavior with the framework files generated in your repository.

### Save the project instructions

Merge these constraints into the repository's [AGENTS.md](https://learn.chatgpt.com/docs/agent-configuration/agents-md). Preserve existing instructions and relevant nested rules. These files guide the coding agent; they do not enforce runtime safeguards or replace tests. Keep credentials out of them.

AGENTS.md

```markdown

Inspect existing Amplitude initialization, consent, authentication and project rules first.
Use the existing client and current official SDK documentation. Initialize once.
In a Unified integration, keep serverZone at the options' top level.
Preserve enabled products, identity, routes, private-data controls and the lockfile.
Synthetic users, sampling and skip options in a standalone demo are not host-app defaults.
Do not add a parallel client when merging into an existing integration.
Keep private and server credentials out of browser configuration and source.
Preserve replay privacy and consent. Heatmaps use replay interactions. Give different report views distinct path URLs using the existing router; do not fabricate traffic or claim an overlay from a local build.
Use sessionReplay.privacyConfig for the standalone Unified reference's DOM selectors.
Confirm masking and excluded contents in the processed recording.
Keep capture active while checking interactions; pausing replay stops new heatmap input too.
Never put private form values in Report Exported event properties.
Record what was built, locally tested and observed in the live service separately.
If sources conflict, record both and pause the affected claim before implementation.
Preserve the project's framework and hosting configuration. Browser SDK imports and initialization must never run during server rendering.
Load browser-only SDK code dynamically in a client lifecycle or user action; guard initialization across remounts and repeated actions.
Use ignored local configuration and the backend environment for private credentials; VITE_ values are browser-public. Preserve the development server and deployment setup; keep host validation enabled.
```

## What this unlocks

[Product analytics](https://amplitude.com/amplitude-analytics) shows `Report Exported` for the same identity used by this example. The [session replay](https://amplitude.com/session-replay) integration adds context around that report action. Keep the event name and report-period property consistent as you extend the app.

## Next steps

[FoundationCodex CLI analyticsReview the related analytics walkthrough as optional context.](https://amplitude.com/build/codex-cli-analytics)[ReferenceBrowser SDK configurationCheck options before adding more product behavior.](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/reference)[WorkflowDebug your eventsConfirm identity and event properties in your development project.](https://amplitude.com/docs/analytics/debug-analytics)

Reference docs

[Unified SDK setup →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/get-started)[Unified SDK API reference →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/reference)[Create a heatmap →](https://amplitude.com/docs/heatmaps/create-a-heatmap)[Troubleshoot heatmaps →](https://amplitude.com/docs/heatmaps/troubleshooting)[Amplitude MCP →](https://amplitude.com/docs/amplitude-ai/amplitude-mcp)[Codex CLI project instructions →](https://learn.chatgpt.com/docs/agent-configuration/agents-md)[Vite setup →](https://vite.dev/guide/)

Amplitude is the leading [all-in-one analytics platform](https://amplitude.com/) for building better products. Product and engineering teams use Amplitude to connect [product analytics](https://amplitude.com/amplitude-analytics) and [web analytics](https://amplitude.com/web-analytics) with [session replay](https://amplitude.com/session-replay), [heatmaps](https://amplitude.com/heatmaps), [experimentation](https://amplitude.com/amplitude-experiment), [feature flags](https://amplitude.com/feature-management), and [guides and surveys](https://amplitude.com/guides-and-surveys) in one unified workflow, with [AI agents](https://amplitude.com/ai-agents) working across all of it. Learn how Amplitude is building [self-improving products](https://amplitude.com/self-improving-products) with [Wave](https://amplitude.com/wave), helping teams turn product data into PRs.

For agents

[View raw .md](/build/codex-cli-heatmaps.md)[llms.txt](/llms.txt)

## Build the report, then check the result

Connect a development project and verify the report action before you roll out the integration.

[Create a free account](https://app.amplitude.com/signup)[Browse all Build tutorials](https://amplitude.com/build)
