Skip to main content

Advanced Configuration

Customize Bily’s behavior with advanced configuration options.

Initialization Options

type BilyConfig = {
  verbose?: boolean;      // Enable detailed logging
  persistQueue?: boolean; // Enable event queue persistence
  sourceUrl?: string;     // Override source URL
  userAgent?: string;     // Override user agent
  ip?: string;           // Override IP address
  referrer?: string;     // Override referrer
};

init('your-domain-tracking-id', {
  verbose: true,          // Enable logging in development
  persistQueue: true,     // Enable event persistence
  sourceUrl: 'https://custom-domain.com'
});

Event Queue & Retry Mechanism

The browser SDK includes a robust event queue system with persistence and retry capabilities:
// Enable event queue persistence
init('your-domain-tracking-id', {
  persistQueue: true  // Store failed events in localStorage
});
When enabled:
  • Failed events are stored in localStorage
  • Automatic retry with exponential backoff
  • Events persist across page reloads
  • Queued events are processed in order

Circuit Breaker Pattern

The SDK implements a circuit breaker pattern to handle failures gracefully:
// The circuit breaker is enabled by default with these settings:
const circuitBreakerConfig = {
  maxFailures: 5,              // Max consecutive failures before opening
  cooldownPeriod: 60000,       // Cooldown period in milliseconds (1 minute)
  halfOpenMaxAttempts: 3       // Max attempts in half-open state
};
The circuit breaker:
  1. Prevents overwhelming failed endpoints
  2. Automatically recovers after cooldown
  3. Implements half-open state for recovery
  4. Manages retry attempts intelligently
These settings are internal and not currently user-configurable.

Custom Event Aliases

track('Custom Event', {
  eventAlias: 'my_custom_event',
  metadata: {
    customField1: 'value1',
    customField2: 'value2'
  }
});

TypeScript Integration

import { BilyEvent, BilyPayload } from '@bilyai/types';

function trackEvent(event: BilyEvent, payload: BilyPayload) {
  // Your tracking logic
}

Next.js Integration

// pages/_app.tsx
import { BilyProvider } from '@bilyai/react';
import type { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <BilyProvider 
      domainTracking={process.env.NEXT_PUBLIC_BILY_DOMAIN}
      options={{ verbose: process.env.NODE_ENV === 'development' }}
    >
      <Component {...pageProps} />
    </BilyProvider>
  );
}

export default MyApp;

Custom Client Data

track('Login', {
  client: {
    id: getBilyTrackingId(),
    email: '[email protected]',
    metadata: {
      accountType: 'premium',
      subscriptionTier: 'enterprise'
    }
  }
});

Enhanced Validation

The SDK performs comprehensive validation of event payloads:
// Email validation
track('Newsletter', {
  client: {
    email: '[email protected]'  // Must be valid email format
  }
});

// Product validation
track('Product Viewed', {
  products: [{
    id: 'prod_123',           // Required
    name: 'Example Product',   // Required
    price: 99.99,             // Must be number
    category: 'Electronics'    // Optional
  }]
});

// Order validation
track('Order Completed', {
  order: {
    id: 'order_456',          // Required
    total: 99.99,             // Must be number
    currency: 'USD'           // Must be valid currency code
  }
});

Error Handling

The SDK includes multiple layers of error protection:
  1. Input Validation
// Invalid payload will throw validation error
track('Custom Event', {
  client: {
    email: 'invalid-email'  // Will throw validation error
  }
});
  1. Circuit Breaker & Queue
// Network failures are handled automatically
track('Custom Event', payload);  // Will be queued if endpoint fails
  1. Manual Error Handling (if needed)
try {
  track('Custom Event', payload);
} catch (error) {
  if (error.name === 'ValidationError') {
    console.error('Invalid payload:', error.message);
  } else {
    console.error('Tracking failed:', error);
  }
}

Best Practices

  1. Use TypeScript for better type safety
  2. Enable verbose mode in development
  3. Enable persistQueue in production for reliability
  4. Handle validation errors appropriately
  5. Use environment variables for configuration
  6. Monitor circuit breaker status in verbose mode
  7. Test with invalid payloads in development

Next Steps