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.
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 collectionAgentDetector.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 collectionsetTimeout(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
For larger applications that need a consistent analytics interface across multiple pages/components, consider creating a universal analytics wrapper that incorporates agent detection:
// analytics.jsimport 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 implementationsexport 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 providersconst 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 usualanalytics.track('PageView', { page: '/home' });analytics.track('ButtonClick', { buttonId: 'signup-button' });// Agent data will be automatically added once detection is complete
Send detection results to a real-time data processing system like Firebase, Supabase, or a custom WebSocket server
Build a dashboard that shows current traffic breakdowns
Set up alerts for unusual patterns in agent traffic
// Example with Firebaseimport { initializeApp } from 'firebase/app';import { getDatabase, ref, set } from 'firebase/database';import AgentDetector from '@superline-ai/agent-detection';// AgentDetector.init(...);// Initialize Firebaseconst firebaseApp = initializeApp({ // your firebase config});const db = getDatabase(firebaseApp);// After detectionconst result = await AgentDetector.finalizeDetection();// Update real-time dashboard dataset(ref(db, 'traffic/' + Date.now()), { timestamp: new Date().toISOString(), isAgent: result.isAgent, confidence: result.confidence, page: window.location.pathname, referrer: document.referrer});
Session Stitching
For multi-page applications, ensure consistent agent detection across pages:
// At the start of each page loadimport AgentDetector from '@superline-ai/agent-detection';// Assuming providers are imported/created:// const metadataProvider = new BrowserMetadataProvider();// const eventsProvider = new BrowserEventProvider();let detector = null; // Hold detector instancefunction initializeDetection() { // Check if we have a previous detection result const savedResult = localStorage.getItem('agent_detection_result'); if (savedResult) { // Use the existing result for immediate classification const parsed = JSON.parse(savedResult); console.log('Using cached detection result:', parsed); // Still perform detection in the background to improve accuracy if (!detector) { const metadataProvider = new BrowserMetadataProvider(); // Example const eventsProvider = new BrowserEventProvider(); // Example detector = new AgentDetector(metadataProvider, eventsProvider); } AgentDetector.init({ autoStart: true }); setTimeout(async () => { // Update the stored result with fresh detection const result = await AgentDetector.finalizeDetection(); localStorage.setItem('agent_detection_result', JSON.stringify({ isAgent: result.isAgent, confidence: result.confidence, lastUpdated: new Date().toISOString() })); }, 5000); return parsed; } else { // No existing result, perform new detection if (!detector) { const metadataProvider = new BrowserMetadataProvider(); // Example const eventsProvider = new BrowserEventProvider(); // Example detector = new AgentDetector(metadataProvider, eventsProvider); } AgentDetector.init({ autoStart: true }); // Return a promise that resolves when detection is complete return new Promise((resolve) => { setTimeout(async () => { const result = await AgentDetector.finalizeDetection(); // Store for future page loads localStorage.setItem('agent_detection_result', JSON.stringify({ isAgent: result.isAgent, confidence: result.confidence, lastUpdated: new Date().toISOString() })); resolve(result); }, 5000); }); }}
A/B Testing Integration
Ensure A/B tests consider agent status:
// Example with Google Optimize or similar// Assuming detector instance is availableasync function initializeExperiments() { // Get agent detection result first const result = await AgentDetector.finalizeDetection(); // Only include real users in experiments if (!result.isAgent) { // Initialize your A/B testing tool initializeOptimize(); // Activate experiments activateExperiments(); } else { // For agents, show the default experience console.log('Agent detected, showing default experience'); }}