Skip to main content

Web SDK

The Inhouse Web SDK allows you to track user interactions, events, and performance metrics in your web applications. It provides comprehensive analytics and deep linking capabilities for modern web experiences.

Installation

NPM Package

Install the SDK using npm:
npm install @inhouse/web

CDN

Include the SDK directly from CDN:
<script src="https://cdn.inhouse.co/web-sdk.js"></script>

ES6 Modules

Import the SDK in your ES6 modules:
import { Inhouse } from '@inhouse/web';

Quick Start

Basic Setup

Initialize the SDK with your project configuration:
import { Inhouse } from '@inhouse/web';

// Initialize the SDK
Inhouse.init({
  apiKey: 'YOUR_API_KEY',
  projectId: 'YOUR_PROJECT_ID',
  environment: 'production' // or 'development'
});

// Track a page view
Inhouse.track('page_view', {
  url: window.location.href,
  title: document.title,
  referrer: document.referrer
});

Configuration Options

Inhouse.init({
  // Required
  apiKey: 'YOUR_API_KEY',
  projectId: 'YOUR_PROJECT_ID',
  
  // Optional
  environment: 'production', // 'production' | 'development' | 'staging'
  debug: false, // Enable debug logging
  batchSize: 10, // Number of events to batch
  batchTimeout: 5000, // Batch timeout in milliseconds
  
  // User identification
  userId: 'user_123', // Current user ID
  userProperties: {
    email: '[email protected]',
    plan: 'premium',
    signupDate: '2024-01-15'
  },
  
  // Custom settings
  customDomain: 'https://yourdomain.com',
  enableDeepLinking: true,
  enablePerformanceTracking: true
});

Event Tracking

Basic Events

Track user interactions and page views:
// Page view tracking
Inhouse.track('page_view', {
  url: window.location.href,
  title: document.title,
  referrer: document.referrer,
  pageType: 'product',
  category: 'electronics'
});

// Button click tracking
Inhouse.track('button_click', {
  buttonText: 'Add to Cart',
  buttonId: 'add-cart-btn',
  page: 'product-page',
  productId: 'prod_123'
});

// Form submission tracking
Inhouse.track('form_submit', {
  formName: 'contact_form',
  formType: 'contact',
  fields: ['name', 'email', 'message']
});

// Link click tracking
Inhouse.track('link_click', {
  linkUrl: 'https://example.com',
  linkText: 'Learn More',
  linkType: 'external',
  page: 'homepage'
});

Custom Events

Track business-specific events:
// E-commerce events
Inhouse.track('product_view', {
  productId: 'prod_123',
  productName: 'Wireless Headphones',
  category: 'Electronics',
  price: 99.99,
  currency: 'USD'
});

Inhouse.track('add_to_cart', {
  productId: 'prod_123',
  productName: 'Wireless Headphones',
  quantity: 1,
  price: 99.99,
  cartTotal: 99.99
});

Inhouse.track('purchase', {
  orderId: 'order_456',
  total: 99.99,
  currency: 'USD',
  products: [
    { id: 'prod_123', name: 'Wireless Headphones', price: 99.99 }
  ]
});

// User engagement events
Inhouse.track('video_play', {
  videoId: 'video_123',
  videoTitle: 'Product Demo',
  duration: 120,
  platform: 'youtube'
});

Inhouse.track('download', {
  fileType: 'pdf',
  fileName: 'product-guide.pdf',
  fileSize: 2048000
});

Event Properties

Add context to your events:
Inhouse.track('user_action', {
  // Required
  action: 'button_click',
  
  // Context
  page: 'product-page',
  section: 'product-details',
  
  // User context
  userId: 'user_123',
  userType: 'premium',
  
  // Business context
  productId: 'prod_123',
  category: 'electronics',
  
  // Custom properties
  campaign: 'summer-sale',
  source: 'email-newsletter',
  timestamp: new Date().toISOString()
});

User Identification

Setting User Properties

Identify and track users across sessions:
// Set user ID
Inhouse.identify('user_123');

// Set user properties
Inhouse.setUserProperties({
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  company: 'Acme Corp',
  plan: 'premium',
  signupDate: '2024-01-15',
  lastLogin: new Date().toISOString()
});

// Update specific properties
Inhouse.setUserProperty('plan', 'enterprise');
Inhouse.setUserProperty('lastPurchase', new Date().toISOString());

User Segmentation

Group users by properties for targeted analytics:
// Set user segments
Inhouse.setUserProperty('segment', 'high-value');
Inhouse.setUserProperty('cohort', '2024-Q1');
Inhouse.setUserProperty('lifetime', 'new');

// Track segment-specific events
if (Inhouse.getUserProperty('segment') === 'high-value') {
  Inhouse.track('premium_feature_used', {
    feature: 'advanced_analytics',
    usage: 'daily'
  });
}

Deep Linking

Web-to-App Navigation

Enable seamless navigation between web and mobile apps:
// Check if mobile app is available
Inhouse.checkAppAvailability().then(available => {
  if (available) {
    // Try to open app with deep link
    Inhouse.openApp('product/123');
  } else {
    // Fallback to web or app store
    window.location.href = 'https://apps.apple.com/app/your-app';
  }
});

// Handle deep link clicks
document.getElementById('deep-link-btn').addEventListener('click', () => {
  Inhouse.track('deep_link_click', {
    destination: 'product/123',
    source: 'web-page'
  });
  
  Inhouse.openApp('product/123');
});
Configure deep linking behavior:
Inhouse.init({
  // ... other config
  deepLinking: {
    enabled: true,
    fallbackUrl: 'https://yourdomain.com/fallback',
    appStoreUrl: 'https://apps.apple.com/app/your-app',
    playStoreUrl: 'https://play.google.com/store/apps/details?id=your.app',
    customScheme: 'yourapp://'
  }
});

Performance Tracking

Core Web Vitals

Track performance metrics automatically:
Inhouse.init({
  // ... other config
  performance: {
    trackCoreWebVitals: true,
    trackPageLoad: true,
    trackResourceTiming: true,
    trackUserTiming: true
  }
});

// Custom performance tracking
Inhouse.track('performance_metric', {
  metric: 'custom_timing',
  value: 1500, // milliseconds
  page: 'product-page',
  component: 'product-gallery'
});

Custom Performance Metrics

Track application-specific performance:
// Track API response times
const startTime = performance.now();
fetch('/api/products')
  .then(response => response.json())
  .then(data => {
    const duration = performance.now() - startTime;
    
    Inhouse.track('api_performance', {
      endpoint: '/api/products',
      duration: duration,
      status: 'success',
      responseSize: JSON.stringify(data).length
    });
  })
  .catch(error => {
    const duration = performance.now() - startTime;
    
    Inhouse.track('api_performance', {
      endpoint: '/api/products',
      duration: duration,
      status: 'error',
      error: error.message
    });
  });

Session Management

Session Tracking

Monitor user sessions and engagement:
// Session events are tracked automatically
// Custom session tracking
Inhouse.track('session_start', {
  referrer: document.referrer,
  landingPage: window.location.href,
  userAgent: navigator.userAgent
});

// Track session duration
let sessionStart = Date.now();
window.addEventListener('beforeunload', () => {
  const sessionDuration = Date.now() - sessionStart;
  
  Inhouse.track('session_end', {
    duration: sessionDuration,
    pages: Inhouse.getSessionPages(),
    events: Inhouse.getSessionEvents()
  });
});

Session Properties

// Set session properties
Inhouse.setSessionProperty('campaign', 'summer-sale');
Inhouse.setSessionProperty('source', 'google-ads');

// Get session information
const sessionId = Inhouse.getSessionId();
const sessionStart = Inhouse.getSessionStart();
const sessionProperties = Inhouse.getSessionProperties();

Error Tracking

Automatic Error Tracking

Track JavaScript errors automatically:
Inhouse.init({
  // ... other config
  errorTracking: {
    enabled: true,
    trackUnhandledErrors: true,
    trackNetworkErrors: true,
    includeStackTraces: true
  }
});

Custom Error Tracking

Track application-specific errors:
// Track form validation errors
function validateForm(formData) {
  try {
    // Validation logic
    if (!formData.email) {
      throw new Error('Email is required');
    }
    
    // Process form
    submitForm(formData);
    
  } catch (error) {
    Inhouse.track('validation_error', {
      error: error.message,
      form: 'contact_form',
      field: 'email',
      userInput: formData.email
    });
    
    // Show error to user
    showError(error.message);
  }
}

// Track API errors
function handleApiError(error, endpoint) {
  Inhouse.track('api_error', {
    error: error.message,
    endpoint: endpoint,
    statusCode: error.status,
    userAgent: navigator.userAgent,
    timestamp: new Date().toISOString()
  });
}

Privacy and Compliance

GDPR Compliance

Handle user consent and data privacy:
Inhouse.init({
  // ... other config
  privacy: {
    gdprCompliant: true,
    requireConsent: true,
    dataRetentionDays: 365,
    anonymizeIp: true
  }
});

// Set user consent
Inhouse.setConsent({
  analytics: true,
  marketing: false,
  necessary: true
});

// Check consent status
if (Inhouse.hasConsent('analytics')) {
  Inhouse.track('user_action', { action: 'button_click' });
}

Data Anonymization

// Anonymize user data
Inhouse.anonymizeUser();

// Set data retention
Inhouse.setDataRetention({
  events: 90, // days
  userProperties: 365, // days
  sessions: 30 // days
});

Advanced Features

Event Batching

Optimize performance with event batching:
Inhouse.init({
  // ... other config
  batching: {
    enabled: true,
    batchSize: 20,
    batchTimeout: 10000, // 10 seconds
    maxBatchSize: 100
  }
});

// Force flush events
Inhouse.flush();

Custom Transport

Use custom transport for events:
Inhouse.init({
  // ... other config
  transport: {
    type: 'custom',
    send: (events) => {
      // Custom event sending logic
      return fetch('/api/analytics', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(events)
      });
    }
  }
});

Plugin System

Extend functionality with plugins:
// Custom plugin
const CustomPlugin = {
  name: 'custom_plugin',
  
  initialize: (config) => {
    console.log('Custom plugin initialized');
  },
  
  track: (event, properties) => {
    // Custom tracking logic
    console.log('Custom tracking:', event, properties);
  }
};

// Register plugin
Inhouse.use(CustomPlugin);

Testing and Debugging

Debug Mode

Enable debug logging:
Inhouse.init({
  // ... other config
  debug: true
});

// Debug methods
Inhouse.debug('User clicked button');
Inhouse.debug('Event tracked:', { event: 'button_click', properties: {} });

Testing Tools

// Mock mode for testing
Inhouse.init({
  // ... other config
  mock: true
});

// Test event tracking
Inhouse.track('test_event', { test: true });

// Verify events
const events = Inhouse.getMockEvents();
console.log('Mock events:', events);

Integration Examples

React Integration

import React, { useEffect } from 'react';
import { Inhouse } from '@inhouse/web';

function ProductPage({ productId }) {
  useEffect(() => {
    // Track page view
    Inhouse.track('page_view', {
      page: 'product',
      productId: productId
    });
  }, [productId]);

  const handleAddToCart = () => {
    Inhouse.track('add_to_cart', {
      productId: productId,
      quantity: 1
    });
    // Add to cart logic
  };

  return (
    <div>
      <h1>Product Details</h1>
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  );
}

Vue.js Integration

<template>
  <div>
    <h1>Product Details</h1>
    <button @click="addToCart">Add to Cart</button>
  </div>
</template>

<script>
import { Inhouse } from '@inhouse/web';

export default {
  name: 'ProductPage',
  props: ['productId'],
  
  mounted() {
    Inhouse.track('page_view', {
      page: 'product',
      productId: this.productId
    });
  },
  
  methods: {
    addToCart() {
      Inhouse.track('add_to_cart', {
        productId: this.productId,
        quantity: 1
      });
      // Add to cart logic
    }
  }
};
</script>

Vanilla JavaScript

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
  Inhouse.init({
    apiKey: 'YOUR_API_KEY',
    projectId: 'YOUR_PROJECT_ID'
  });
  
  // Track page view
  Inhouse.track('page_view', {
    url: window.location.href,
    title: document.title
  });
  
  // Set up event listeners
  setupEventTracking();
});

function setupEventTracking() {
  // Track button clicks
  document.querySelectorAll('[data-track]').forEach(button => {
    button.addEventListener('click', (event) => {
      const trackData = JSON.parse(button.dataset.track);
      
      Inhouse.track('button_click', {
        ...trackData,
        buttonText: button.textContent,
        buttonId: button.id
      });
    });
  });
  
  // Track form submissions
  document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', (event) => {
      Inhouse.track('form_submit', {
        formName: form.name || form.id,
        formType: form.dataset.type || 'general'
      });
    });
  });
}

Best Practices

Event Naming

  1. Use Consistent Naming: Follow a consistent naming convention
  2. Be Descriptive: Use clear, descriptive event names
  3. Use Snake Case: Use snake_case for event names
  4. Group Related Events: Use prefixes for related events

Property Management

  1. Standardize Properties: Use consistent property names across events
  2. Validate Data: Ensure property values are valid and consistent
  3. Limit Property Count: Keep properties focused and relevant
  4. Document Properties: Document your event schema

Performance Optimization

  1. Batch Events: Use event batching for high-frequency events
  2. Debounce Tracking: Debounce rapid-fire events
  3. Lazy Loading: Load SDK only when needed
  4. Minimize Payload: Keep event payloads small

Privacy and Security

  1. User Consent: Always respect user privacy preferences
  2. Data Minimization: Only collect necessary data
  3. Secure Transmission: Use HTTPS for all data transmission
  4. Regular Audits: Regularly review data collection practices

Troubleshooting

Common Issues

  • Check API key and project ID
  • Verify network connectivity
  • Check browser console for errors
  • Verify SDK initialization
  • Verify event tracking calls
  • Check property values
  • Review event naming
  • Test in debug mode
  • Enable event batching
  • Reduce event frequency
  • Check for memory leaks
  • Monitor network requests

Debug Commands

// Check SDK status
console.log('SDK Status:', Inhouse.getStatus());

// View configuration
console.log('Configuration:', Inhouse.getConfig());

// Check user properties
console.log('User Properties:', Inhouse.getUserProperties());

// View session info
console.log('Session Info:', Inhouse.getSessionInfo());

Next Steps

Mobile SDKs

Integrate with React Native apps.

API Reference

Use the REST API for advanced integration.

Deep Linking

Set up deep linking for web-to-app navigation.

Analytics

Understand your analytics data.
Need help with the Web SDK? Check our API documentation or contact [email protected].