Custom Analytics Integration

This guide shows you how to integrate Superline Agent Detection with any analytics platform of your choice, beyond the specific integrations we’ve covered for Google Analytics and Mixpanel.

Universal Integration Approach

Regardless of which analytics platform you’re using, the core integration pattern remains similar: detect AI agents and include this information in your analytics data. Here’s a universal approach that works with any platform.

1

Initialize Agent Detection

First, initialize Superline Agent Detection early in your application:

import AgentDetector from '@superline-ai/agent-detection';

// Initialize with automatic data collection
AgentDetector.init({
  debug: false,
  autoStart: true
});
2

Create Detection Function

Create a function that performs detection and returns the result:

async function detectAgent() {
  try {
    // Allow sufficient time for data collection before calling
    // Assuming 'detector' instance is accessible here
    const result = await AgentDetector.finalizeDetection();
    return {
      isAgent: result.isAgent,
      confidence: result.confidence
    };
  } catch (error) {
    console.error('Agent detection error:', error);
    return null;
  }
}
3

Integrate with Your Analytics

Call the detection function at the appropriate time and add the result to your analytics platform:

// Wait for sufficient data collection
setTimeout(async () => {
  const agentData = await detectAgent();
  
  if (agentData) {
    // Send to your analytics platform
    // This is a generic example - adapt it to your specific platform
    analytics.identify({
      isAgent: agentData.isAgent,
      agentConfidence: agentData.confidence
    });
    
    // Set as global property for future events
    analytics.setGlobalProperty('isAgent', agentData.isAgent);
  }
}, 5000); // 5 seconds delay

Platform-Specific Examples

Here are integration examples for several popular analytics platforms:

Creating a Universal Analytics Wrapper

For larger applications that need a consistent analytics interface across multiple pages/components, consider creating a universal analytics wrapper that incorporates agent detection:

// analytics.js
import AgentDetector from '@superline-ai/agent-detection';
// Assuming providers are imported/created:
// const metadataProvider = new BrowserMetadataProvider();
// const eventsProvider = new BrowserEventProvider();

class Analytics {
  constructor(options = {}) {
    this.providers = options.providers || [];
    this.detectionComplete = false;
    this.agentData = null;
    this.eventQueue = [];
    this.detector = null; // Hold detector instance
    
    // Initialize agent detection
    // Assuming providers are available
    this.detector = new AgentDetector(metadataProvider, eventsProvider);
    this.AgentDetector.init({ autoStart: true });
    
    // Set up detection
    setTimeout(this.detectAgent.bind(this), options.detectionDelay || 5000);
  }
  
  async detectAgent() {
    try {
      const result = await this.AgentDetector.finalizeDetection();
      this.agentData = {
        isAgent: result.isAgent,
        confidence: result.confidence
      };
      
      // Track detection event
      this.track('AgentDetectionComplete', this.agentData);
      
      // Process queued events
      this.detectionComplete = true;
      this.processQueue();
      
      return this.agentData;
    } catch (error) {
      console.error('Agent detection error:', error);
      this.detectionComplete = true;
      this.processQueue();
      return null;
    }
  }
  
  processQueue() {
    while (this.eventQueue.length > 0) {
      const { eventName, properties } = this.eventQueue.shift();
      this.trackToProviders(eventName, properties);
    }
  }
  
  track(eventName, properties = {}) {
    // Add agent data if available
    if (this.agentData) {
      properties = {
        ...properties,
        isAgent: this.agentData.isAgent,
        agentConfidence: this.agentData.confidence
      };
      
      // Track immediately
      this.trackToProviders(eventName, properties);
    } else if (this.detectionComplete) {
      // Detection tried but failed, track anyway
      this.trackToProviders(eventName, properties);
    } else {
      // Queue the event for later
      this.eventQueue.push({ eventName, properties });
    }
  }
  
  trackToProviders(eventName, properties) {
    // Send to all configured providers
    this.providers.forEach(provider => {
      try {
        provider.track(eventName, properties);
      } catch (error) {
        console.error(`Error tracking to provider ${provider.name}:`, error);
      }
    });
  }
  
  // Add a new analytics provider
  addProvider(provider) {
    this.providers.push(provider);
  }
}

// Example provider implementations
export const GoogleAnalyticsProvider = {
  name: 'Google Analytics',
  track: (eventName, properties) => {
    if (window.gtag) {
      window.gtag('event', eventName, properties);
    }
  }
};

export const MixpanelProvider = {
  name: 'Mixpanel',
  track: (eventName, properties) => {
    if (window.mixpanel) {
      window.mixpanel.track(eventName, properties);
    }
  }
};

export default Analytics;

Usage of this wrapper:

import Analytics, { GoogleAnalyticsProvider, MixpanelProvider } from './analytics';

// Initialize with your preferred providers
const analytics = new Analytics({
  providers: [
    GoogleAnalyticsProvider,
    MixpanelProvider,
    // Add your custom providers
    {
      name: 'Custom Backend',
      track: (eventName, properties) => {
        // Your custom implementation
        fetch('https://your-api.com/track', {
          method: 'POST',
          body: JSON.stringify({ eventName, properties })
        });
      }
    }
  ],
  detectionDelay: 5000 // 5 seconds
});

// Track events as usual
analytics.track('PageView', { page: '/home' });
analytics.track('ButtonClick', { buttonId: 'signup-button' });

// Agent data will be automatically added once detection is complete

Best Practices for Any Platform

Regardless of which analytics platform you’re using, follow these best practices:

Consistent Property Names

Use consistent property names across all events (e.g., always use isAgent rather than mixing is_agent, isBot, etc.)

Include Confidence

Always include the confidence for nuanced analysis.

Delay Detection

Wait 3-5 seconds before performing detection to allow sufficient data collection

Graceful Fallbacks

Handle detection failures gracefully to ensure analytics continue to work even if detection fails

Advanced Topics

Next Steps

Now that you’ve learned how to integrate Superline Agent Detection with any analytics platform, consider exploring our other guides: