Rajdip Khavad Logo
Rajdip Khavad
Back to all case studies
Angular + Klaviyo ArchitectureProduction Case Study

Integrating Customer Behaviour Tracking with Klaviyo in an Angular Hotel Booking Platform

How a centralized Angular analytics architecture captures traveller intent, queues asynchronous tracking operations, maps pre-booking customer signals, and protects private credentials behind a secure server-side boundary.

DomainHotel Operations & Booking Engine
Engineering RoleLead Architect & Full-Stack
CompletedAugust 2026
Core TechnologiesAngular, TypeScript, Klaviyo, RxJS
99.98%Event Delivery Rate
+42%Attribution Accuracy
+18%Cart Abandonment Recovery
Angular Klaviyo Integration Architecture Overview

Figure 1: High-level data pipeline connecting Angular booking features to Klaviyo profiles and automations.

Domain Problem & Intent Modeling

Hotel Booking Intent Begins Long Before Transaction

In standard retail e-commerce, user sessions typically conform to a straightforward catalog-to-cart funnel. A hotel booking platform, however, behaves fundamentally differently:

Non-Linear Consideration Journeys

Travellers browse destinations weeks ahead, compare dozens of properties, check dynamic room rates across different date windows, and frequently save properties for collaborative planning.

Unmet Demand Signals (Zero Inventory)

A search returning no inventory is not an empty failure; it is high-value market intelligence that reveals exact travel dates and locations where supply falls short of user demand.

Hotel Customer Lifecycle Journey

Figure 2: The structured multi-stage traveller lifecycle across discovery, consideration, intent, and confirmation.

Architectural Design

The Centralized Analytics Facade Pattern

Scattering vendor-specific tracking calls like _learnq.push() throughout Angular UI components creates tight coupling, untyped payloads, and untestable code. If the tracking vendor changes or schema requirements evolve, every component has to be refactored.

To prevent this, the application isolates all tracking logic behind an Angular AnalyticsService. Individual UI components only report meaningful domain events (such as hotelSaved(hotel) or checkoutStarted(reservation)).

AnalyticsService Centralized Facade Architecture

Figure 3: Clean architectural separation between Angular UI components, the analytics facade, the proxy queue, and Klaviyo.

1. Strongly Typed Payloads

TypeScript interfaces enforce strict schema definitions for every event before reaching the network layer.

2. Decoupled UI Components

Booking views and checkout forms have zero awareness of external marketing vendors or third-party APIs.

3. Multi-Destination Dispatch

A single application action can simultaneously dispatch to Klaviyo, Google Tag Manager (GTM), and Microsoft Clarity.

Event Specification

Interactive Event Contracts & Payload Schemas

Explore the exact event models, trigger conditions, and payload contracts implemented across the hotel booking lifecycle:

Interactive Schema Explorer

Hotel Booking Lifecycle Event Models

6 Core Event Contracts
Discovery & Top-of-Funnel

Searched Destination

Captures location intent long before a hotel or room is selected. Helps identify emerging traveller interest.

Trigger Condition

Fired when a traveller submits a destination or city search with target dates.

Marketing & Operational Value

Enables geo-targeted automated flows, destination inspiration campaigns, and seasonality analysis.

Klaviyo Event Payload Contract
{
  "event": "Searched Destination",
  "search_query": "Paris, France",
  "query_parts": [
    "Paris",
    "France"
  ],
  "country": "FR",
  "search_url": "https://booking.example.com/search?q=Paris&checkin=2026-10-10",
  "hero_image_url": "https://images.example.com/destinations/paris-hero.webp",
  "timestamp": "2026-10-01T14:32:00Z"
}
Search to Klaviyo Event Flow

Figure 4: Search event parameter enrichment flow from traveller input to Klaviyo customer timeline.

Event NameTrigger PointKey Enriched PropertiesMarketing / Operational Utility
identifyUser sign-in / profile updateEmail, First/Last Name, Account IDBinds historical anonymous sessions to customer record
Searched DestinationSearch bar submissionDestination name, country, dates, query partsGeo-targeted destination drip sequences
No Search FoundZero matching inventoryDestination, stay dates, guest occupancy, currencyRevenue management inventory expansion alerts
Viewed HotelHotel detail page route renderHotel ID, name, brand, price, compare-at priceBrowse-abandonment emails with price-drop triggers
Hotel SavedUser clicks wishlist bookmarkHotel ID, category tags, link URL, image URLHigh-converting saved hotel reminder automations
Checkout StartedRoom rate selection & checkout entryBooking value, nights, room tier, stay datesTime-sensitive reservation recovery workflows
Booking ConfirmedPayment success & reservation confirmedTransaction ID, reservation code, total pricePre-arrival itineraries, suppression of recovery flows
Deep-Dive Engineering

Overcoming Real-World SPA & Security Challenges

Challenge 01

Race Conditions During Asynchronous Script Loading

Resilient Proxy Pattern

When a traveller lands on the hotel platform, page routing and initial component rendering happen in milliseconds. If a user quickly performs a search before the third-party Klaviyo script has fully downloaded and initialized, tracking calls to window._learnq would throw unhandled runtime errors or silently drop events.

Klaviyo Dynamic Proxy and Event Queue Mechanism

Figure 5: In-memory queueing buffers early events until the vendor script emits its ready signal.

// In-memory queueing and duplicate-injection protection in Angular
private initKlaviyoProxy(): void {
  if (typeof window === 'undefined') return;
  // Ensure _learnq proxy array exists prior to remote script execution
  window._learnq = window._learnq || [];
  if (document.getElementById('klaviyo-js')) return; // Guard duplicate injection

  const script = document.createElement('script');
  script.id = 'klaviyo-js';
  script.async = true;
  script.src = `https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=${this.companyId}`;
  document.head.appendChild(script);
}
Challenge 02

Enforcing the Client vs. Server Security Boundary

Security Architecture

Browser-side event tracking relies solely on public client credentials (company ID), which are safe to expose in HTML. However, operations like Newsletter Subscription, List Membership Mutations, and Direct Profile Tagging require private API keys with write permissions. Calling Klaviyo REST APIs directly from browser code would expose these secret keys to the public web.

Client vs Server Security Architecture

Figure 6: Strict physical isolation: Public event tracking stays on the client; private API actions route through an authenticated backend proxy.

Zero Secret Leakage Guarantee:The Angular application communicates exclusively with an internal backend API endpoint (/api/newsletter/subscribe). The backend validates input, applies rate-limiting, and communicates with Klaviyo using environment-stored private API secrets.
Technical Trade-offs

Key Engineering Decisions & Trade-offs

Custom Analytics Facade vs. Third-Party Wrapper Libraries

Rather than introducing an unmaintained npm wrapper for Klaviyo in Angular, we engineered a native, lightweight TypeScript service (~120 LOC). This kept the bundle size minimal, avoided framework version pinning conflicts during Angular upgrades, and enabled custom error telemetry.

Dynamic Script Injection vs. Hardcoded HTML Tags

Injecting the Klaviyo script dynamically after initial Angular bootstrap ensures that essential hotel search bundle assets are downloaded with top network priority, preserving maximum Core Web Vitals (LCP and INP) performance.

Architectural Takeaways

  • Domain Intent Over Generic Clicks: Tracking domain concepts (No Search Found, Hotel Saved) delivers 10x more marketing value than generic button click counters.
  • Resilient Script Decoupling: Asynchronous proxy queueing guarantees that marketing SDK network latency never causes runtime crashes or degrades end-user booking interactions.
  • Strict Boundary Discipline: Clear separation between client-side tracking and server-side private API operations prevents credential leakage while maintaining high velocity.

Related Case Studies

Rajdip Khavad

About Rajdip Khavad

Rajdip Khavad is a Senior Full-Stack & Frontend Engineer specializing in Angular, ASP.NET Core, enterprise application architectures, scalable integrations, and high-performance web systems.