Welcome to Encatch Docs
SDK Guide

JavaScript Web SDK

Complete integration guide for the e-Ncatch JavaScript SDK with advanced configuration options and best practices

The encatch JavaScript SDK provides seamless integration for web applications, enabling automated feedback collection, user analytics, and behavior tracking with minimal setup.

Quick Start

Get e-Ncatch running in your application in under 5 minutes with below steps.

Installation & Initialization

Install the e-Ncatch JavaScript SDK using your preferred package manager:

@encatch/web-sdk

After installation, import and initialize the SDK in your application:

import { Encatch } from '@encatch/web-sdk';

// Initialize the SDK
const encatch = new Encatch();
encatch.init('<YOUR_PROJECT_API_KEY>');

Add the following script to the <head> section of your HTML, preferably just before the closing </head> tag. Replace <your_project_api_key> with your actual project API key from the e-Ncatch dashboard.

<html>
    <head>
        ....other head content
        <script type="module">
            (function(){window.encatch||(window.encatch={_i:[],apiKey:"",config:{host:void 0,isAutoCaptureEnabled:!0,themeMode:"light",language:"en"},initialized:!1,chunkUrlLoader:i=>window.encatch.config.host+i,init(i,e){if(window.encatch.initialized)return;window.encatch.apiKey=i,e!=null&&e.host&&(window.encatch.config.host=e.host),e!=null&&e.identity&&(window.encatch.config.identity=e.identity),(e==null?void 0:e.processAfterIdentitySet)!==void 0?window.encatch.config.processAfterIdentitySet=e.processAfterIdentitySet:window.encatch.config.processAfterIdentitySet=!1,(e==null?void 0:e.isAutoCaptureEnabled)!==void 0&&(window.encatch.config.isAutoCaptureEnabled=e.isAutoCaptureEnabled),e!=null&&e.themeMode?window.encatch.config.themeMode=e.themeMode:window.encatch.config.themeMode="light",e!=null&&e.language?window.encatch.config.language=e.language:window.encatch.config.language="en",window.encatch.initialized=!0;const g=`${window.encatch.config.host}/plugin/sdk/encatch-web-sdk.js`,t=document.createElement("script");t.src=g,t.type="module",t.async=!0;const n=document.head.firstChild;n?document.head.insertBefore(t,n):document.head.appendChild(t);const d=document.createElement("div");d.id="enisght-root",document.body.appendChild(d)}},["trackEvent","stopSession","identify","resetSession","openFeedbackById","openFeedbackByName","setThemeMode","setLanguage","verifyFeedbackIds","forceFetchEligibleFeedbacks","capturePageScrollEvent"].forEach(i=>{window.encatch[i]=(...e)=>{window.encatch._i.push([i,...e])}}))})();
            encatch.init('<YOUR_PROJECT_API_KEY>');
        </script>
    </head>
<body>
    ....other body content
</body>
</html>

Note on Server Side Rendering Frameworks (SSR)

encatch web is a client side SDK and relies on window object to be available. So ensure it is not used in server side components.

Framework Examples

import { Encatch } from '@encatch/web-sdk';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const encatch = new Encatch();
    encatch.init('<YOUR_PROJECT_API_KEY>');
  }, []);

  return <div>Your React App</div>;
}
import { Encatch } from '@encatch/web-sdk';
import { onMounted } from 'vue';

export default {
  setup() {
    onMounted(() => {
      const encatch = new Encatch();
      encatch.init('<YOUR_PROJECT_API_KEY>');
    });
  }
}

Create a Svelte Component

Create a new component file src/lib/EncatchComponent.svelte:

<script>
  import { onMount } from 'svelte';
  import { Encatch } from '@encatch/web-sdk';

  onMount(() => {
    const encatch = new Encatch();
    encatch.init('<YOUR_PROJECT_API_KEY>');
  });
</script>

Include in Layout

Add the component to your root layout file src/routes/+layout.svelte:

<script>
  import EncatchComponent from '$lib/EncatchComponent.svelte';
</script>

<EncatchComponent />
<slot />

Create an Angular Service

Create a new service file src/app/services/encatch.service.ts:

import { Injectable } from '@angular/core';
import { Encatch } from '@encatch/web-sdk';

@Injectable({
  providedIn: 'root'
})
export class EncatchService {
  private encatch: any;

  constructor() {
    this.encatch = new Encatch();
    this.encatch.init('<YOUR_PROJECT_API_KEY>');
  }
}

Include in App Component

Add the service to your main app component src/app/app.component.ts:

import { Component } from '@angular/core';
import { EncatchService } from './services/encatch.service';

@Component({
  selector: 'app-root',
  template: `
    <router-outlet></router-outlet>
  `
})
export class AppComponent {
  constructor(private encatchService: EncatchService) {}
}

Create a Component

Create a new component file src/components/EncatchComponent.tsx:

import { onMount } from 'solid-js';
import { Encatch } from '@encatch/web-sdk';

export default function EncatchComponent() {
  onMount(() => {
    const encatch = new Encatch();
    encatch.init('<YOUR_PROJECT_API_KEY>');
  });

  return null;
}

Include in App

Add the component to your main app file src/App.tsx:

import { Component } from 'solid-js';
import EncatchComponent from './components/EncatchComponent';

const App: Component = () => {
  return (
    <>
      <EncatchComponent />
      <div>Your SolidJS App</div>
    </>
  );
};

export default App;

Create a Client Component

Create a new component file components/EncatchComponent.tsx:

'use client';
import { Encatch } from '@encatch/web-sdk';
import { useEffect } from 'react';

export default function EncatchComponent({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    const encatch = new Encatch();
    encatch.init('<YOUR_PROJECT_API_KEY>');
  }, []);

  return (
    <>
      {children}
    </>
  );
}

Include in Layout

Add the component to your root layout file app/layout.tsx:

import EncatchComponent from '@/components/EncatchComponent';

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      <EncatchComponent/>
      <main>
        {children}
      </main>
      <Footer />
    </>
  )
}

Create a Plugin

Create a new plugin file plugins/encatch.client.ts:

import { Encatch } from '@encatch/web-sdk';

export default defineNuxtPlugin(() => {
  const encatch = new Encatch();
  encatch.init('<YOUR_PROJECT_API_KEY>');
});

Alternative: Use in App.vue

You can also initialize the SDK directly in your app.vue file:

<template>
  <div>
    <NuxtPage />
  </div>
</template>

<script setup>
import { Encatch } from '@encatch/web-sdk';

onMounted(() => {
  const encatch = new Encatch();
  encatch.init('<YOUR_PROJECT_API_KEY>');
});
</script>

Create a Client Component

Create a new component file components/EncatchComponent.tsx:

'use client';
import { Encatch } from '@encatch/web-sdk';
import { useEffect } from 'react';

export default function EncatchComponent() {
  useEffect(() => {
    const encatch = new Encatch();
    encatch.init('<YOUR_PROJECT_API_KEY>');
  }, []);

  return null;
}

Include in Layout

Add the component to your layout file:

import EncatchComponent from '@/components/EncatchComponent';

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      <EncatchComponent/>
      <main>
        {children}
      </main>
      <Footer />
    </>
  )
}

For enterprise version

encatch.init('<YOUR_PROJECT_API_KEY>', {
  host: 'https://your-encatch-instance'
});

How to use

Session Management

Control user session lifecycle for accurate analytics and user journey tracking.

For best practices, username field should be difficult to guess or not easily reproducible. Don't use fields like email, mobile or system numeric ids.

Explicitly starts a new user session. Useful when you want manual control over session creation.

// Start a new session as a visitor
encatch.startSession();

// Start a new session with known user
encatch.startSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'user@example.com',
    name: 'John Doe',
    plan: 'enterprise'
  },
  '$set_once': {
    signup_date: '2025-01-15',
    initial_referrer: 'google.com'
  }
});

Use Cases:

  • Manual session control
  • Explicit session initialization
  • Custom session management workflows
  • Starting sessions with user context

Updates the current session with new user properties or session data. Works like an upsert operation - creates a session if one doesn't exist, or updates the existing session if it does. Primarily used when a user logs in after a session has already been started on the website.

// Update session when user logs in (after anonymous session was started)
encatch.updateSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'user@example.com',
    name: 'John Doe',
    plan: 'premium',
    last_login: '2025-01-20'
  },
  '$set_once': {
    first_login: '2025-01-15'
  }
});

// Update user properties during an active session
encatch.updateSession({
  '$set': {
    plan: 'enterprise',
    role: 'admin',
    last_activity: '2025-01-20T10:30:00Z'
  },
  '$unset': ['trial_status']
});

Use Cases:

  • Updating anonymous session with user info after login
  • Changing user properties during active session

Terminates the current user session and clears all downloaded feedback configurations. If you want to switch to visitor mode after stopping a session, you need to explicitly start a new session.

// End current session (clears feedback configurations)
encatch.stopSession();

// To switch to visitor mode, start a new session
encatch.startSession();

Use Cases:

  • User logout (best use case - completely stops session and clears feedback configs)
  • Complete session termination
  • Clearing all user data and feedback configurations

Creates a new session while maintaining user identity. Useful for session refresh scenarios. Accepts a type parameter to control the reset behavior.

// Soft reset (default) - only resets session ID
encatch.resetSession();
encatch.resetSession({ type: 'soft' });

// Hard reset - logs user out and switches to visitor mode
encatch.resetSession({ type: 'hard' });

Reset Types:

  • soft (default): Only resets the session ID. User identity and feedback configurations are maintained. Useful for applications with long session durations where you want to tag user actions during inactivity periods.
  • hard: Logs the user out and switches to visitor mode. Clears user identity and applies visitor-specific feedback configurations if configured.

Use Cases:

  • Soft reset: Session renewal without re-authentication
  • Hard reset: Complete user logout and visitor mode switch
  • Maintaining user identity across session boundaries

User Property Management

The SDK supports advanced property operations for user identification and session management. These operations allow you to set, update, and remove user properties with different behaviors.

Property Operations Overview: Complete examples showing how all operations work together in real-world scenarios.

// 1. Start session with initial user data
encatch.startSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'john@example.com',
    name: 'John Doe',
    plan: 'free'
  },
  '$set_once': {
    signup_date: '2025-01-15',
    initial_referrer: 'google.com',
    original_plan: 'free'
  }
});

// 2. Update session when user logs in
encatch.updateSession({
  '$set': {
    email: 'john.doe@company.com', // Updated email
    plan: 'premium',               // Upgraded plan
    last_login: '2025-01-20',
    company: 'Tech Corp'
  },
  '$set_once': {
    first_login: '2025-01-15',
    work_email_verified: true
  }
});

// 3. Track user engagement and metrics
encatch.updateSession({
  '$counter': {
    login_count: 1,
    session_duration: 25, // minutes
    page_views: 8,
    features_used: 3
  }
});

// 4. Clean up deprecated properties
encatch.updateSession({
  '$set': {
    plan: 'enterprise',
    status: 'active'
  },
  '$unset': ['trial_status', 'beta_features', 'deprecated_preferences']
});

Common Workflow Patterns: Real-world examples showing how property operations work together in typical application scenarios.

// Pattern 1: Anonymous → Authenticated User
encatch.startSession(); // Start anonymous session
// ... user browses ...
encatch.updateSession({ user_name: 'user123', '$set': { email: 'user@example.com' } });

// Pattern 2: User Profile Updates with Metrics
encatch.updateSession({
  '$set': { name: 'New Name', preferences: { theme: 'dark' } },
  '$set_once': { name_change_count: 1 },
  '$counter': { profile_updates: 1, theme_changes: 1 }
});

// Pattern 3: Account Cleanup
encatch.updateSession({
  '$set': { status: 'active' },
  '$unset': ['suspended_reason', 'old_email']
});

// Pattern 4: Session Reset during logout
encatch.resetSession({ type: 'hard' });

Set Operation: Overwrites existing property values or creates new ones. Used for mutable user data.

// Basic $set usage in updateSession
encatch.updateSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'user@example.com',
    name: 'John Doe',
    plan: 'premium',
    last_login: '2025-01-20',
    preferences: { theme: 'dark', notifications: true }
  }
});

// $set in startSession
encatch.startSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'user@example.com',
    signup_date: '2025-01-15'
  }
});

Use Cases:

  • Updating user profile information
  • Changing user preferences or settings
  • Modifying subscription plans or roles
  • Tracking last activity timestamps

Set Once Operation: Sets a property value only if it doesn't already exist. Perfect for immutable data.

// Basic $set_once usage
encatch.updateSession({
  '$set_once': {
    initial_referrer: 'google.com',
    signup_date: '2025-01-15',
    first_device: 'Chrome on MacOS',
    original_plan: 'free'
  }
});

// $set_once with $set
encatch.updateSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    email: 'newemail@example.com',
    plan: 'premium'
  },
  '$set_once': {
    first_login: '2025-01-15',
    referral_source: 'direct'
  }
});

Use Cases:

  • Tracking first-time user attributes
  • Recording signup information
  • Capturing initial referral sources
  • Storing original user state data

Counter Operation: Increments or decrements numeric property values with the value provided. Perfect for tracking usage metrics and counters.

// Basic $counter usage
encatch.updateSession({
  '$counter': {
    login_count: 1, //incrementing login count
    happy_metric: -1, // an example where the user has been facing non 2xxx http status from the API
    purchase_total: 29.99,
    support_tickets: -1 // Can decrement too
  }
});

// $counter with other operations
encatch.updateSession({
  user_name: 'UUID_OF_USER',
  '$set': {
    last_login: '2025-01-20',
    status: 'active'
  },
  '$set_once': {
    account_created: '2025-01-15'
  },
  '$counter': {
    total_logins: 1,
    session_count: 1,
  }
});

// Tracking user engagement
encatch.updateSession({
  '$counter': {
    articles_read: 1,
    videos_watched: 2,
    downloads: 3,
    time_spent_minutes: 15
  }
});

Use Cases:

  • Tracking user engagement metrics (page views, logins, etc.)
  • Counting user actions and interactions
  • Managing usage quotas and limits
  • Decrementing counters (like remaining credits)

Notes:

  • Counter operations on non-existent properties initialize them to the provided value
  • Supports both positive (increment) and negative (decrement) values
  • Works with integers and decimal numbers

Unset Operation: Removes properties from user profile. Useful for cleaning up deprecated data.

// Basic $unset usage
encatch.updateSession({
  '$unset': ['old_property', 'deprecated_field', 'temporary_data']
});

// $unset with $set
encatch.updateSession({
  '$set': {
    plan: 'enterprise',
    status: 'active'
  },
  '$unset': ['trial_status', 'beta_features', 'deprecated_preferences']
});

Use Cases:

  • Removing deprecated properties
  • Cleaning up temporary data
  • Clearing old user states
  • Removing obsolete user attributes

Triggers

The e-Ncatch SDK provides comprehensive event tracking capabilities with four distinct approaches: automatic event capture for common interactions, custom event tracking for business-specific metrics, scroll event tracking for engagement analysis, and manual feedback control for programmatic trigger management.

Programmatic Feedback Display

Override automatic triggering with manual control over feedback form presentation.

Display a specific feedback form by its unique identifier.

Example Usage:

// Basic usage
encatch.openFeedbackById('feedback_config_123');

// With theme and language overrides
encatch.openFeedbackById('feedback_config_123', 'dark', 'es');

// With event context for tracking
encatch.openFeedbackById('feedback_config_123', 'light', 'en', 'button_click');

Use Cases:

  • Programmatic feedback form display
  • Integration with existing UI components
  • Custom feedback triggers
  • A/B testing specific feedback forms

Parameters:

Prop

Type

Display a feedback form by its configured title/name.

Example Usage:

// Open by form title
encatch.openFeedbackByName('Product Satisfaction Survey');

// With customization options
encatch.openFeedbackByName('Feature Feedback', 'dark', 'fr', 'feature_usage');

Use Cases:

  • Content-driven feedback display
  • User-friendly feedback triggers
  • CMS integration scenarios
  • Non-technical implementation

Parameters:

Prop

Type

Best Practice: Use feedback IDs for programmatic control and names for content-driven scenarios. IDs are more stable across configuration changes.

Auto-captured Events: The SDK automatically tracks common user interactions and page events without any manual implementation required.

Configuration:

// Disable automatic event tracking
encatch.init('<YOUR_PROJECT_API_KEY>', {
  isAutoCaptureEnabled: false
});

// Enable specific auto-events only
encatch.init('<YOUR_PROJECT_API_KEY>', {
  isAutoCaptureEnabled: true,
  autoCaptureConfig: {
    pageViews: true,
    clicks: true,
    errors: true,
    performance: false,
    forms: true
  }
});

Use Cases:

  • Basic user behavior analytics without custom implementation
  • Page engagement and navigation tracking
  • Error monitoring and debugging
  • Performance analysis
  • Form abandonment analysis

Automatic Context Enrichment: All auto-captured events are automatically enhanced with:

  • Current page path and title
  • Session information and user identity
  • Device and browser metadata
  • Timestamp and user agent
  • Geographic location (if available)

Custom Events: Track specific events that are unique to your application's needs and business logic using the trackEvent method.

trackEvent(eventName, properties?)

Use Cases:

  • User behavior analytics
  • Feature usage tracking
  • Conversion funnel analysis
  • Custom business metrics
  • Application-specific interactions
  • A/B test tracking
  • User journey mapping

Parameters:

Prop

Type

Example Usage:

// Basic event tracking
encatch.trackEvent('page_view');

// E-commerce events
encatch.trackEvent('purchase_completed', {
  productId: 'prod_123',
  amount: 99.99,
  currency: 'USD',
  category: 'electronics',
  quantity: 2,
  payment_method: 'credit_card'
});

// User interaction tracking
encatch.trackEvent('button_click', {
  buttonId: 'cta-subscribe',
  location: 'hero-section',
  action: 'newsletter_signup',
  timestamp: Date.now()
});

// Feature usage tracking
encatch.trackEvent('feature_used', {
  feature: 'advanced_search',
  filters_applied: ['price', 'category', 'rating'],
  results_count: 25,
  search_time: 1.2
});

// Video engagement
encatch.trackEvent('video_interaction', {
  video_id: 'tutorial_101',
  action: 'play',
  current_time: 45,
  total_duration: 180,
  quality: '720p'
});

// Form analytics
encatch.trackEvent('form_step_completed', {
  form_name: 'onboarding',
  step: 2,
  step_name: 'personal_info',
  time_spent: 120,
  completion_rate: 0.75
});

Event Enhancement: The SDK automatically enriches tracked events with:

  • Current page path and title
  • Session information and user identity
  • Device and browser metadata
  • Timestamp and user agent
  • Geographic location (if available)

Scroll Events: Track user engagement and reading behavior through scroll depth analytics, perfect for content optimization and user experience insights.

captureScrollEvent(scrollPercent)

Use Cases:

  • Content engagement analysis
  • Reading behavior tracking
  • Page performance optimization
  • A/B testing scroll depth
  • Content length optimization
  • User experience research
  • Conversion funnel analysis

Parameters:

Prop

Type

Example Usage:

// Basic page scroll tracking
window.addEventListener('scroll', () => {
  const scrollPercent = Math.round(
    (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
  );
  encatch.captureScrollEvent(scrollPercent);
});

// Article reading progress
const articleElement = document.getElementById('article-content');
articleElement.addEventListener('scroll', () => {
  const scrollPercent = Math.round(
    (articleElement.scrollTop / (articleElement.scrollHeight - articleElement.clientHeight)) * 100
  );
  encatch.captureScrollEvent(scrollPercent);
});

// Custom container scroll tracking
const scrollableDiv = document.getElementById('product-list');
scrollableDiv.addEventListener('scroll', () => {
  const scrollPercent = Math.round(
    (scrollableDiv.scrollTop / (scrollableDiv.scrollHeight - scrollableDiv.clientHeight)) * 100
  );
  encatch.captureScrollEvent(scrollPercent);
});

// Manual scroll capture
encatch.captureScrollEvent(25);  // 25% scrolled
encatch.captureScrollEvent(50);  // 50% scrolled
encatch.captureScrollEvent(75);  // 75% scrolled
encatch.captureScrollEvent(100); // 100% scrolled

Scroll Milestones:

// Track common scroll milestones
const milestones = [25, 50, 75, 100];
let trackedMilestones = new Set();

window.addEventListener('scroll', () => {
  const scrollPercent = Math.round(
    (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
  );

  milestones.forEach(milestone => {
    if (scrollPercent >= milestone && !trackedMilestones.has(milestone)) {
      encatch.captureScrollEvent(milestone);
      trackedMilestones.add(milestone);

      // Optional: Track milestone achievement
      encatch.trackEvent('scroll_milestone_reached', {
        milestone: milestone,
        page: window.location.pathname,
        time_to_reach: Date.now() - pageLoadTime
      });
    }
  });
});

Note: This method accepts a single number representing the scroll percentage (0-100). Your application must calculate the scroll percentage from any scrollable element before passing it to the method.

Best Practices:

  • Use throttling/debouncing for scroll event listeners to avoid performance issues
  • Track scroll milestones (25%, 50%, 75%, 100%) for content engagement analysis
  • Combine scroll tracking with custom events for comprehensive user journey analysis
  • Consider privacy implications and implement appropriate user consent

UI Customization

Dynamically control the appearance and localization of feedback forms and interfaces.

setThemeMode(theme)

Prop

Type

Example Usage:

// Basic theme switching
encatch.setThemeMode('dark');   // Switch to dark theme
encatch.setThemeMode('light');  // Switch to light theme

Use Cases:

  • Dark mode toggle implementation
  • System theme synchronization
  • User preference persistence
  • Accessibility compliance

setLanguage(languageCode)

Prop

Type

Example Usage:

// Language localization
encatch.setLanguage('es');      // Spanish
encatch.setLanguage('fr');      // French
encatch.setLanguage('de');      // German
encatch.setLanguage('YOUR_ADMIN_CONFIG_LANGUAGE_CODE');

Use Cases:

  • Internationalization (i18n) implementation
  • Multi-language application support
  • User language preference persistence
  • Browser language detection and fallback

Note: Language changes affect all subsequent feedback forms. You may ideally call this when user switches languages in your application.

Advanced SDK Methods

How is this guide?