Skip to main content
RapidDev - Software Development Agency
lovable-integrationsEdge Function Integration

How to Integrate Lovable with Crazy Egg

Add Crazy Egg heatmaps and A/B testing to a Lovable app by injecting the Crazy Egg script tag in your index.html using your Account ID. For accessing snapshot data and A/B test results programmatically, create a Supabase Edge Function that calls the Crazy Egg API with credentials stored in Cloud → Secrets. The script injection alone enables heatmaps and recordings — no API key is needed for basic tracking.

What you'll learn

  • How to inject the Crazy Egg tracking script into a Lovable Vite+React application for automatic heatmap generation
  • How to configure Crazy Egg for single-page application route tracking in a React Router app
  • How to create a Supabase Edge Function that accesses Crazy Egg's API for snapshot and A/B test data
  • How to set up Crazy Egg A/B tests for UI variations in your Lovable app without modifying tracking code
  • How to use Crazy Egg's snapshot reports to identify click patterns and scroll depth across your app's pages
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate17 min read20 minutesAnalyticsMarch 2026RapidDev Engineering Team
TL;DR

Add Crazy Egg heatmaps and A/B testing to a Lovable app by injecting the Crazy Egg script tag in your index.html using your Account ID. For accessing snapshot data and A/B test results programmatically, create a Supabase Edge Function that calls the Crazy Egg API with credentials stored in Cloud → Secrets. The script injection alone enables heatmaps and recordings — no API key is needed for basic tracking.

Adding Crazy Egg Heatmaps and A/B Testing to Your Lovable App

Crazy Egg is the conversion optimization tool of choice for teams who want to understand how visitors interact with specific pages — where they click, how far they scroll, and whether UI elements are being noticed or ignored. Unlike session replay tools that record individual user sessions, Crazy Egg aggregates click data across all visitors into heatmap visualizations that make patterns immediately obvious: the button everyone clicks, the navigation item nobody sees, the form field where users abandon. For Lovable app builders, Crazy Egg answers the page-level UX questions that inform landing page optimization, feature discoverability improvements, and conversion rate optimization.

Crazy Egg's integration with a Lovable Vite+React app is simpler than most analytics tools because the core functionality (heatmaps, scroll maps, and recordings) requires only a script tag injected into the HTML head. The script loads asynchronously from Crazy Egg's CDN and immediately begins tracking click and scroll events on every page your users visit. The Account ID in the script URL identifies your Crazy Egg account — this is a public identifier visible in your HTML source, similar to GA4's Measurement ID.

For single-page applications built with React Router, Crazy Egg needs to know when the page path changes so it starts a new snapshot for each route. Crazy Egg's SPA tracking feature handles this automatically for most React Router configurations. The A/B testing feature in Crazy Egg allows you to define visual variations of page elements through Crazy Egg's editor interface, with the JavaScript variant injection handled by the Crazy Egg script without any changes to your Lovable codebase. This is particularly useful for testing changes to landing pages and conversion flows where you want to validate impact before implementing permanently in Lovable.

Integration method

Edge Function Integration

Crazy Egg integrates with Lovable primarily through the client-side script tag injection in index.html using your Account ID. The script automatically generates heatmaps and scroll maps for every page in your Lovable app. For accessing snapshot reports and A/B test results via the Crazy Egg API, a Supabase Edge Function proxies API requests with credentials stored in Cloud → Secrets. The basic heatmap and recording functionality requires no API key — just the script tag.

Prerequisites

  • A Lovable account with an existing project that has at least a few pages to track
  • A Crazy Egg account — free 30-day trial at crazyegg.com, then plans starting at $29/month
  • Your Crazy Egg Account ID — visible in the tracking script URL at app.crazyegg.com → Account → Tracking Script
  • For API access: a Crazy Egg API key from Account Settings (available on Plus and above plans)
  • At least a few hundred page visits to generate meaningful heatmap data — heatmaps require traffic to populate

Step-by-step guide

1

Get your Crazy Egg Account ID and add the tracking script

Crazy Egg's heatmap tracking starts with a single script tag in your HTML head. Log in to your Crazy Egg account at app.crazyegg.com. To find your Account ID, click your name in the top-right corner and select Account Settings, then look for the 'Tracking Code' or 'Installation Code' section. You will see a script tag that looks like this: script type='text/javascript' src='//script.crazyegg.com/pages/scripts/0012/3456.js' async='async' — the numbers in the URL path (0012/3456 in this example) form your Account ID. The format is a 4-digit number followed by another 4-digit number, separated by a slash. In your Lovable project, ask Lovable to add the Crazy Egg script to your index.html file. The script must be placed in the HTML head section for reliable loading. The script tag should use the async attribute to prevent blocking page rendering. Use the VITE_CRAZY_EGG_ACCOUNT_ID environment variable if you want to configure the Account ID through environment variables, though since it is a public identifier, hardcoding it in the script URL is also acceptable. After adding the script, go to your Lovable project's Cloud tab, click Secrets, and add VITE_CRAZY_EGG_ACCOUNT_ID with your Account ID value. For API access (used in the Edge Function for programmatic data access), also add CRAZY_EGG_API_KEY if you have one from account settings. Verify the script is loading correctly by opening your app in the browser and checking the Network tab in developer tools — you should see a request to script.crazyegg.com that returns HTTP 200. In Crazy Egg's dashboard, go to Snapshots → Add New Snapshot and enter your app's URL. Crazy Egg will begin recording visitor clicks when users visit the page, building up the heatmap data over time.

Lovable Prompt

Add the Crazy Egg tracking script to index.html. Place it in the HTML head section as an async script. The src should be '//script.crazyegg.com/pages/scripts/' followed by the account ID from VITE_CRAZY_EGG_ACCOUNT_ID formatted as four digits, a forward slash, and four more digits (e.g., '0012/3456'). Also create a type declaration for the CE2 global in src/types/crazyegg.d.ts so the Crazy Egg API is typed in TypeScript.

Paste this in Lovable chat

src/types/crazyegg.d.ts
1// src/types/crazyegg.d.ts
2declare global {
3 interface Window {
4 CE2?: {
5 set: (key: string, value: string | number | boolean) => void;
6 identify: (email: string) => void;
7 event: (event_name: string) => void;
8 };
9 ce2?: {
10 ready: (callback: () => void) => void;
11 };
12 }
13}
14
15export {};

Pro tip: Crazy Egg's script loads asynchronously, which means it may not be fully initialized when your React components mount. If you need to call Crazy Egg's JavaScript API (CE2.set(), CE2.identify()) from components, wait for the CE2 global to be available using window.ce2?.ready() callback or by polling for window.CE2 with a short interval.

Expected result: The Crazy Egg script is in the HTML head of your app. Network requests to script.crazyegg.com show HTTP 200 status. In Crazy Egg's dashboard, creating a new snapshot for your app's URL shows 'Tracking Code Detected' status. The CE2 global TypeScript declaration allows typed API calls from components.

2

Configure Crazy Egg for React Router single-page application tracking

Crazy Egg's default behavior tracks a new 'page view' when the browser URL changes via a full page reload. In a React Router single-page application, route changes happen without full page reloads — Crazy Egg needs to be notified of route changes to correctly separate heatmap data by route, rather than aggregating all clicks into a single snapshot for the initial page load URL. Crazy Egg has built-in SPA support that can be enabled in your snapshot settings. In Crazy Egg's dashboard, go to your snapshot and look for 'Advanced Settings' or 'SPA Tracking' options. Enable the 'Track SPA' or 'Hash and History URL changes' option. This instructs the Crazy Egg script to listen for History API pushState events (which React Router uses for navigation) and automatically start a new snapshot session when the path changes. If automatic SPA detection does not work for your specific React Router configuration, you can manually notify Crazy Egg of route changes using the CE2 JavaScript API. Create a React hook that listens to React Router's location changes and calls the Crazy Egg API method to signal a new page view. This is similar to the GA4 pageview hook pattern. For apps with dynamic routes (like /projects/123 versus /projects/456 — different projects but the same component), you may want to configure Crazy Egg snapshots to use URL patterns rather than exact URLs. In Crazy Egg's snapshot configuration, you can set the URL to include wildcards like /projects/* to aggregate heatmap data across all project pages into a single snapshot. This gives more clicks per snapshot for better heatmap accuracy, at the cost of not differentiating between specific dynamic pages. Create separate snapshots for each important page in your Lovable app: the landing page, the main feature page, the pricing page, the settings page, and the checkout flow steps. Configure each snapshot with the correct URL, enable SPA tracking, and set a meaningful name so you can identify them in the dashboard.

Lovable Prompt

Create a src/hooks/useCrazyEgg.ts hook that integrates Crazy Egg with React Router. Import useLocation from react-router-dom. On every route change, notify Crazy Egg of the new page by calling window.CE2?.event() with the new pathname. This ensures Crazy Egg tracks each route as a separate page for accurate per-route heatmap data.

Paste this in Lovable chat

src/hooks/useCrazyEgg.ts
1// src/hooks/useCrazyEgg.ts
2import { useEffect } from 'react';
3import { useLocation } from 'react-router-dom';
4
5export function useCrazyEgg() {
6 const location = useLocation();
7
8 useEffect(() => {
9 // Notify Crazy Egg of SPA route changes
10 // CE2 may not be initialized on first load — the async script handles the initial page
11 if (typeof window !== 'undefined' && window.CE2) {
12 window.CE2.event('SPA Page View');
13 }
14 }, [location.pathname]);
15}
16
17// Optional: identify authenticated users in Crazy Egg recordings
18export function identifyCrazyEggUser(email: string) {
19 if (typeof window !== 'undefined' && window.CE2) {
20 window.CE2.identify(email);
21 }
22}

Pro tip: Crazy Egg snapshots need a minimum number of visits to display a heatmap (typically 100-500 visits depending on plan). For new apps with low traffic, it may take days or weeks for meaningful heatmap data to accumulate. Set up snapshots early and let Crazy Egg collect data in the background while you continue building.

Expected result: The useCrazyEgg hook is called from App.tsx. Navigating between routes in the app triggers the CE2.event call. In Crazy Egg's dashboard, separate snapshot data accumulates for different routes as visitors navigate. The heatmap for each route shows only clicks that occurred on that specific route.

3

Set up a Crazy Egg A/B test for a key conversion element

Crazy Egg's A/B testing feature allows you to test visual variations of page elements — button text, colors, sizes, positions — without modifying your Lovable codebase. Crazy Egg injects the variation JavaScript through its own CDN, and your Lovable app only needs the tracking script to be installed. To create an A/B test in Crazy Egg, go to app.crazyegg.com → A/B Tests → Create New Test. Select the URL of the page you want to test. Crazy Egg opens a visual editor showing your page as it would appear to visitors. Use the editor to select an element — for example, the main CTA button — and define the variation: change the button text from 'Start Free Trial' to 'Get Started Free', or change the button color from gray to blue. Define your test goal: typically a click on the CTA button itself, a form submission, or navigation to a specific URL (like a signup confirmation page). Crazy Egg will track which variant achieves higher goal completion rates. Set the traffic split — the default 50/50 split is recommended for most tests. Crazy Egg A/B tests are activated and deactivated entirely from Crazy Egg's dashboard — no code changes are needed in your Lovable app after the initial script installation. This is the key advantage: your development team does not need to create feature flags or deploy code changes for each marketing test. When a test concludes, implement the winning variant permanently in Lovable. For monitoring A/B test results inside your Lovable app (without opening Crazy Egg's dashboard), create a Supabase Edge Function that fetches test performance data from Crazy Egg's API. This is only available on certain Crazy Egg plan tiers — check whether your plan includes API access before building this.

Lovable Prompt

Create a Supabase Edge Function called 'crazy-egg-data' that fetches A/B test results from the Crazy Egg API. Use CRAZY_EGG_API_KEY from Deno secrets with Basic auth. Fetch the list of active A/B tests and their performance metrics (variant names, visitor counts, conversion rates). Return the data as JSON. Create a simple ABTestResults React component that calls this Edge Function and displays a table of active tests with their current conversion rates.

Paste this in Lovable chat

supabase/functions/crazy-egg-data/index.ts
1// supabase/functions/crazy-egg-data/index.ts
2import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
3
4const corsHeaders = {
5 'Access-Control-Allow-Origin': '*',
6 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
7};
8
9serve(async (req) => {
10 if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
11
12 try {
13 const apiKey = Deno.env.get('CRAZY_EGG_API_KEY');
14 if (!apiKey) {
15 return new Response(JSON.stringify({ error: 'CRAZY_EGG_API_KEY not configured' }), {
16 status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
17 });
18 }
19
20 const { resource = 'snapshots' } = req.method === 'POST'
21 ? await req.json().catch(() => ({}))
22 : {};
23
24 // Crazy Egg API uses Basic auth with API key
25 const credentials = btoa(`${apiKey}:`);
26 let apiUrl = 'https://app.crazyegg.com/api';
27
28 if (resource === 'snapshots') {
29 apiUrl += '/snapshots';
30 } else if (resource === 'abtests') {
31 apiUrl += '/abtests';
32 } else {
33 return new Response(JSON.stringify({ error: 'Invalid resource' }), {
34 status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
35 });
36 }
37
38 const response = await fetch(apiUrl, {
39 headers: {
40 'Authorization': `Basic ${credentials}`,
41 'Accept': 'application/json',
42 },
43 });
44
45 if (!response.ok) {
46 const errorText = await response.text();
47 console.error('Crazy Egg API error:', response.status, errorText);
48 return new Response(
49 JSON.stringify({ error: `Crazy Egg API returned ${response.status}`, detail: errorText }),
50 { status: response.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
51 );
52 }
53
54 const data = await response.json();
55 return new Response(JSON.stringify(data), {
56 headers: { ...corsHeaders, 'Content-Type': 'application/json' },
57 });
58 } catch (error) {
59 return new Response(JSON.stringify({ error: String(error) }), {
60 status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
61 });
62 }
63});

Pro tip: Crazy Egg A/B tests require a minimum number of visitors per variant to reach statistical significance before declaring a winner — typically 100-500 visitors per variant depending on your expected conversion rate. Running tests for less than two business weeks often does not produce reliable results due to day-of-week traffic patterns.

Expected result: The crazy-egg-data Edge Function is deployed. Calling it with { resource: 'snapshots' } returns a list of Crazy Egg snapshots. The crazy-egg-data function correctly authenticates with the Crazy Egg API and returns structured data for snapshot and A/B test visualization.

Common use cases

Identify which UI elements on the landing page drive conversions

Enable Crazy Egg on your Lovable app's landing page to see exactly where visitors click. The confetti report shows individual clicks colored by traffic source, revealing whether organic search visitors and paid ad visitors click different elements. Scroll maps show what percentage of visitors see the pricing section and CTA button below the fold — often revealing that the most important conversion elements are not being seen.

Lovable Prompt

Add the Crazy Egg tracking script to index.html using the VITE_CRAZY_EGG_ACCOUNT_ID environment variable. Ensure the script loads in the HTML head before the closing head tag. The script URL format is //script.crazyegg.com/pages/scripts/[account_id].js and should be loaded asynchronously with the async attribute.

Copy this prompt to try it in Lovable

Run A/B tests on call-to-action button copy without code changes

Use Crazy Egg's visual A/B testing to test different button copy, colors, and positioning on your Lovable app's key conversion pages without modifying the Lovable codebase. Crazy Egg injects the variations via its own JavaScript, and the results appear in Crazy Egg's dashboard showing which variant achieves higher click rates on the target element.

Lovable Prompt

The Crazy Egg A/B test setup happens in Crazy Egg's dashboard, not in the Lovable code. After the script is installed, go to app.crazyegg.com → A/B Tests → New Test, select your page, and use Crazy Egg's visual editor to define the variant. The test activates automatically without any code changes to the Lovable app. Create a Supabase Edge Function called 'crazy-egg-data' to fetch A/B test results via the Crazy Egg API so test performance can be monitored from inside the Lovable admin panel.

Copy this prompt to try it in Lovable

Monitor scroll depth to optimize content placement across key pages

Use Crazy Egg's scroll map reports to determine what percentage of visitors see each section of your key pages. If only 30% of visitors scroll far enough to see the pricing table, you need to either move the pricing section higher or improve the content above it to encourage scrolling. The scroll map gives you data to make this decision confidently.

Lovable Prompt

After installing the Crazy Egg script, create a SnapshotReport component that fetches scroll depth data from the Crazy Egg API via a Supabase Edge Function. Display the scroll depth percentages for each 10% segment of the page as a bar chart. Fetch snapshot data for the landing page URL and display it in the admin panel so the team can monitor scroll behavior without leaving the app.

Copy this prompt to try it in Lovable

Troubleshooting

Crazy Egg's dashboard shows 'No tracking code detected' for the app URL

Cause: The Crazy Egg script tag was not added to index.html, was placed in the wrong location (in the body instead of head), uses the wrong account ID format, or the script is being blocked by a Content Security Policy.

Solution: Open the browser's Network tab and look for a request to script.crazyegg.com. If no request appears, the script was not loaded — verify the script tag is in the index.html head section and uses the correct URL format: //script.crazyegg.com/pages/scripts/XXXX/XXXX.js. If the request appears but is blocked, check for CSP errors in the console. Use Crazy Egg's Installation Checker tool (app.crazyegg.com → Account → Installation Check) to verify the script is detected on your URL.

Heatmap shows all clicks aggregated on the home page even though users navigate to different routes

Cause: Crazy Egg is not detecting SPA route changes — it is treating the entire app session as a single page view on the initial URL.

Solution: Enable SPA tracking in Crazy Egg's snapshot settings: go to your snapshot → Settings → Advanced → enable 'Track single-page application URL changes'. Also ensure the useCrazyEgg hook is mounted in App.tsx to trigger CE2.event on each route change. Verify the hook is working by watching the browser console for any Crazy Egg-related messages when navigating between pages.

A/B test variations are not appearing in the live app after activation in Crazy Egg

Cause: The Crazy Egg script is loading after the DOM is rendered, causing the A/B test variation injection to conflict with React's virtual DOM management, or the A/B test URL target does not match the actual URL the app is serving.

Solution: Verify the A/B test URL pattern in Crazy Egg exactly matches your app's page URL. Check that the Crazy Egg script loads in the HTML head with the async attribute — the script must initialize before React renders the component that contains the target element. If React re-renders the element after Crazy Egg modifies it, React may overwrite the changes. Consider testing Crazy Egg A/B tests on elements outside React's rendering scope, like the page background or static HTML elements.

Edge Function returns 403 when calling the Crazy Egg API

Cause: The Crazy Egg plan does not include API access, the API key is incorrect, or the API authentication format used does not match what Crazy Egg expects for the account.

Solution: Verify API access is included in your Crazy Egg plan by checking app.crazyegg.com → Account Settings → API. If API access is not shown, it may not be included in your plan tier. Contact Crazy Egg support to confirm API availability. Test the API key directly using curl: curl -H 'Authorization: Basic [base64(apikey:)]' https://app.crazyegg.com/api/snapshots.

Best practices

  • Set up Crazy Egg snapshots for your key pages immediately after installing the script — heatmaps require traffic to populate, and waiting to configure snapshots means losing early visitor data.
  • Use URL patterns with wildcards for dynamic routes in Crazy Egg snapshots (like /products/*) to aggregate clicks across similar pages — individual dynamic pages may not accumulate enough clicks for a statistically meaningful heatmap.
  • Run Crazy Egg A/B tests for at least two full business weeks before analyzing results — day-of-week traffic patterns can skew early results, making a losing variant appear to win if the test ends on an atypical traffic day.
  • Combine Crazy Egg click heatmaps with FullStory session recordings for complete behavioral insight — heatmaps show aggregate patterns while session recordings explain the individual decision-making behind those patterns.
  • Set up A/B test goals to match your actual conversion metrics — if your goal is signups, set the Crazy Egg goal to navigation to the '/confirmation' URL rather than a click on the signup button, which ensures you are measuring actual conversions rather than just button clicks.
  • Review scroll maps monthly for key pages and compare them to changes in conversion rates — drops in scroll depth often precede conversion rate decreases because users stop seeing important page sections.

Alternatives

Frequently asked questions

Does Crazy Egg work with React Router single-page applications?

Yes, with SPA tracking enabled. Enable the 'Track single-page application URL changes' option in each Crazy Egg snapshot's Advanced Settings to detect React Router navigations and create separate heatmap data per route. The useCrazyEgg hook described in Step 2 also manually notifies Crazy Egg of route changes using the CE2.event() API as a reliable fallback.

How many visits are needed before a Crazy Egg heatmap shows meaningful data?

Crazy Egg recommends at least 100 visits per page for a basic heatmap — fewer than this produces sparse data that may not represent real patterns. For accurate scroll maps and A/B test statistical significance, 500-1,000 visits per page gives more reliable insights. Set up Crazy Egg snapshots early and let them collect data over time rather than expecting immediate results.

Can Crazy Egg A/B tests interfere with how my Lovable React app renders?

Potentially yes. Crazy Egg's A/B test variations inject JavaScript that modifies DOM elements after the page loads. In React apps, if React re-renders a component that Crazy Egg has modified, React's virtual DOM diffing may overwrite the Crazy Egg variation. Test A/B test variations thoroughly after activation to verify they render correctly alongside React's rendering lifecycle. Static elements that React does not re-render (like a static hero section background color) are safer for Crazy Egg A/B tests than dynamic React component content.

Is the Crazy Egg Account ID sensitive and should I protect it?

The Crazy Egg Account ID is a public identifier — it is visible in your HTML source and is intentionally public, similar to GA4's Measurement ID. Anyone can view it but cannot use it to access your Crazy Egg account data. The API key (used for programmatic data access) is sensitive and must be kept in Cloud → Secrets. The distinction is the same as other analytics tools: tracking identifiers are public, API keys for reading data are private.

How do I see Crazy Egg heatmaps for pages that require authentication?

Crazy Egg can track authenticated pages, but it cannot render a screenshot for the heatmap overlay since it does not have your users' login credentials. Instead, Crazy Egg's heatmap shows click coordinates on the page layout as it appeared when users interacted with it. You can upload a screenshot of the authenticated page to Crazy Egg as the heatmap background image. Alternatively, use Crazy Egg's recording feature, which captures individual sessions including authenticated content.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.