Segment Troubleshooting & Debugging | OpsBlu Docs

Segment Troubleshooting & Debugging

Diagnose and fix common Segment tracking issues. Covers script loading failures, missing events, data discrepancies, integration conflicts, and.

Overview

This guide helps you diagnose and resolve common Segment tracking issues. Segment is a customer data platform (CDP) that routes data to multiple destinations, making proper configuration essential.

Debug Mode

Enable Debug Mode

Enable debug mode to see detailed tracking information:

// Enable debug mode in Segment
analytics.debug(true);

// Or set on initialization
analytics.load('YOUR_WRITE_KEY', {
  integrations: {
    'All': true,
    'Segment.io': { apiHost: 'api.segment.io/v1' }
  }
});
analytics.debug(true);

Check Segment Loading

Verify Segment (Analytics.js) is loaded correctly:

// Check if analytics object exists
if (typeof analytics !== 'undefined' && analytics.initialized) {
  console.log('Segment loaded successfully');
  console.log('Write key configured');
} else {
  console.error('Segment not loaded');
}

// Check user ID and anonymous ID
if (typeof analytics !== 'undefined') {
  console.log('Anonymous ID:', analytics.user().anonymousId());
  console.log('User ID:', analytics.user().id());
}

Common Issues

No Data Reaching Segment

Symptoms: Tracking code installed but no data in Segment debugger.

Solutions:

  1. Verify write key:
// Check your write key is correct
// Find in Segment Sources → Settings → API Keys

analytics.load('YOUR_WRITE_KEY');

// Verify it's loaded
console.log('Analytics initialized:', analytics.initialized);
  1. Check script installation:
<!-- Segment Analytics.js snippet -->
<script>
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};analytics._writeKey="YOUR_WRITE_KEY";analytics.SNIPPET_VERSION="4.15.3";
  analytics.load("YOUR_WRITE_KEY");
  analytics.page();
  }}();
</script>
  1. Verify network requests:

    • Open DevTools → Network tab
    • Filter by "segment" or "api.segment.io"
    • Look for POST requests to api.segment.io/v1
    • Status should be 200 (Success)
  2. Check Segment Debugger:

    • Go to Segment Sources → Debugger
    • Should see live events within seconds
    • Verify events are properly formatted
  3. Check source enabled:

    • Go to Segment Sources
    • Verify source is enabled (green indicator)
    • Check connection status

Events Not Tracking

Symptoms: track() calls not appearing in Segment.

Solutions:

  1. Verify track() syntax:
// Correct event tracking
analytics.track('Button Clicked', {
  button_name: 'Sign Up',
  page: 'Homepage',
  user_type: 'Free'
});

// Enable debug mode to see tracking
analytics.debug(true);
analytics.track('Test Event', { test: true });
// Check console for details
  1. Wait for ready:
// Ensure Segment is ready before tracking
analytics.ready(function() {
  console.log('Segment ready');
  analytics.track('Page Loaded');
});

// Or use callback
analytics.track('Event Name', {
  property: 'value'
}, function() {
  console.log('Event sent');
});
  1. Check event naming:
    • Event names are case-sensitive
    • Use consistent naming conventions
    • Follow naming best practices
// Good event names
analytics.track('Order Completed');
analytics.track('Video Played');

// Inconsistent naming (creates separate events)
analytics.track('order completed');  // Different case
analytics.track('Order_Completed');  // Different format
  1. Verify properties:
// Valid property types
analytics.track('Purchase', {
  order_id: '12345',
  revenue: 99.99,
  currency: 'USD',
  products: ['SKU123', 'SKU456']
});

// Properties should be JSON-serializable
// Avoid: functions, DOM elements, circular references

Destinations Not Receiving Data

Symptoms: Data in Segment but not reaching destinations (GA, Mixpanel, etc.).

Solutions:

  1. Check destination status:

    • Go to Segment Sources → Destinations
    • Verify destination is enabled (green)
    • Check connection status
  2. Verify destination mappings:

    • Click on destination
    • Check "Mappings" tab
    • Ensure event mappings are configured
  3. Check destination settings:

// Control which destinations receive events
analytics.track('Event Name', {
  property: 'value'
}, {
  integrations: {
    'All': false,           // Disable all by default
    'Google Analytics': true,  // Enable only specific destinations
    'Mixpanel': true
  }
});
  1. Review destination errors:

    • Check Segment Sources → Debugger
    • Look for destination delivery errors
    • Review error messages for each destination
  2. Verify destination credentials:

    • Check API keys, tracking IDs
    • Ensure credentials are current
    • Test connection in destination settings

User Identification Not Working

Symptoms: Users not being identified correctly.

Solutions:

  1. Call identify() correctly:
// Identify user
analytics.identify('user_12345', {
  email: 'user@example.com',
  name: 'John Doe',
  plan: 'premium',
  created_at: new Date().toISOString()
});

// Verify user ID set
console.log('User ID:', analytics.user().id());
console.log('Traits:', analytics.user().traits());
  1. Use alias() for merging identities:
// When user signs up, create alias
// Connect anonymous ID to user ID
analytics.alias('user_12345');

// Then identify
analytics.identify('user_12345', {
  email: 'user@example.com'
});

// IMPORTANT: Only call alias once per user, at signup
  1. Reset identity on logout:
// Reset user identity on logout
analytics.reset();

// Clears user ID and generates new anonymous ID
console.log('New anonymous ID:', analytics.user().anonymousId());
  1. Check trait naming:
// Use consistent trait names
analytics.identify('user_12345', {
  email: 'user@example.com',  // lowercase
  firstName: 'John',          // camelCase
  lastName: 'Doe',
  company: 'Acme Corp'
});

Group Tracking Not Working

Symptoms: Group (account-level) data not tracking.

Solutions:

  1. Call group() correctly:
// Associate user with group (company/account)
analytics.group('company_123', {
  name: 'Acme Corporation',
  plan: 'Enterprise',
  employees: 500,
  industry: 'Technology'
});

// Verify group ID
console.log('Group ID:', analytics.group().id());
console.log('Group traits:', analytics.group().traits());
  1. Track events with group context:
// Events automatically include group context
analytics.track('Feature Used', {
  feature: 'Dashboard',
  user_role: 'Admin'
});
// Group ID included automatically

Page Tracking Issues

Symptoms: Page views not being tracked correctly.

Solutions:

  1. Call page() correctly:
// Track page view
analytics.page();

// With category and name
analytics.page('Products', 'Product Detail');

// With properties
analytics.page('Products', 'Product Detail', {
  product_id: 'SKU123',
  product_name: 'Widget Pro'
});
  1. For single-page applications:
// Call page() on route changes
// Example with React Router
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();

  useEffect(() => {
    analytics.page();
  }, [location]);
}

// Example with Vue Router
router.afterEach((to, from) => {
  analytics.page();
});

Debugging Techniques

Comprehensive Health Check

// Complete Segment diagnostic
function segmentHealthCheck() {
  console.group('Segment Health Check');

  // 1. Check if loaded
  if (typeof analytics === 'undefined') {
    console.error('analytics not defined');
    console.groupEnd();
    return;
  }

  // 2. Check initialization
  console.log('Initialized:', analytics.initialized);

  // 3. Check user
  console.log('User ID:', analytics.user().id() || 'Not set');
  console.log('Anonymous ID:', analytics.user().anonymousId());

  // 4. Check group
  const groupId = analytics.group().id();
  console.log('Group ID:', groupId || 'Not set');

  // 5. Test tracking
  analytics.track('Health Check Test', {
    timestamp: new Date().toISOString()
  });
  console.log('✓ Test event sent');

  console.groupEnd();
}

segmentHealthCheck();

Monitor All Tracking Calls

// Log all Segment calls
const methods = ['track', 'page', 'identify', 'group', 'alias'];

methods.forEach(method => {
  const original = analytics[method];
  analytics[method] = function() {
    console.log(`analytics.${method} called:`, arguments);
    return original.apply(this, arguments);
  };
});

Check Source Middleware

// Add middleware to debug/modify events
analytics.addSourceMiddleware(({ payload, next }) => {
  console.log('Segment event:', payload);

  // Modify payload if needed
  // payload.obj.properties.custom_prop = 'value';

  next(payload);
});

Browser-Specific Issues

Safari ITP (Intelligent Tracking Prevention)

// Segment uses first-party cookies for better ITP compatibility
// Configure cookie settings if needed
analytics.load('YOUR_WRITE_KEY', {
  cookie: {
    domain: '.yourdomain.com',
    secure: true,
    sameSite: 'None'
  }
});

Content Security Policy (CSP)

<!-- Add Segment domains to CSP -->
<meta http-equiv="Content-Security-Policy"
      content="script-src 'self' https://cdn.segment.com 'unsafe-inline';
               connect-src 'self' https://api.segment.io;">

Ad Blockers

// Detect if Segment is blocked
setTimeout(function() {
  if (typeof analytics === 'undefined' || !analytics.initialized) {
    console.warn('Segment likely blocked by ad blocker');

    // Fallback: Use server-side tracking
    // Or alternative analytics
  }
}, 2000);

Data Quality Issues

Duplicate Events

// Prevent duplicate tracking
let eventSent = {};

function trackOnce(eventName, properties) {
  const key = eventName + JSON.stringify(properties);

  if (!eventSent[key]) {
    analytics.track(eventName, properties);
    eventSent[key] = true;

    // Clear after 5 seconds
    setTimeout(() => delete eventSent[key], 5000);
  }
}

trackOnce('Purchase', { order_id: '12345' });

Invalid Properties

// Validate properties before sending
function trackWithValidation(eventName, properties) {
  const validProperties = {};

  for (const key in properties) {
    const value = properties[key];

    // Check if value is JSON-serializable
    try {
      JSON.stringify(value);
      validProperties[key] = value;
    } catch (e) {
      console.warn(`Invalid property ${key}:`, value);
    }
  }

  analytics.track(eventName, validProperties);
}

trackWithValidation('Event', {
  valid: 'string',
  invalid: function() {}  // Will be filtered out
});

Performance Issues

Reduce Payload Size

// Avoid sending large data
analytics.track('Page View', {
  // Don't send entire objects
  // full_page_html: document.body.innerHTML,

  // ✓ Send only necessary data
  page_title: document.title,
  page_url: window.location.href
});

Batch Events

// Segment automatically batches events
// Configure batch settings if needed
analytics.load('YOUR_WRITE_KEY', {
  integrations: {
    'Segment.io': {
      apiHost: 'api.segment.io/v1',
      protocol: 'https'
    }
  }
});

Getting Help

Check Segment Status

Visit status.segment.com for service status.

Use Segment Debugger

  1. Go to Sources → Debugger
  2. View live events as they're sent
  3. Check event payload
  4. See destination delivery status

Contact Support

If issues persist:

  1. Collect debug information:

    • Browser and version
    • Segment write key
    • Console errors/warnings
    • Screenshots from Debugger
  2. Contact Segment Support:

  3. Segment Documentation:

Best Practices

Regular Testing

// Create test suite
function runSegmentTests() {
  console.group('Segment Tests');

  analytics.debug(true);

  // 1. Test page view
  analytics.page('Test Category', 'Test Page');
  console.log('✓ Page tracked');

  // 2. Test event
  analytics.track('Test Event', { test: true });
  console.log('✓ Event tracked');

  // 3. Test identify
  analytics.identify('test_user', { email: 'test@example.com' });
  console.log('✓ User identified');

  // 4. Test group
  analytics.group('test_company', { name: 'Test Corp' });
  console.log('✓ Group set');

  console.groupEnd();
}

runSegmentTests();

Monitor in Production

// Log Segment errors
window.addEventListener('error', function(e) {
  if (e.message && e.message.includes('segment')) {
    console.error('Segment error:', e);
    // Send to error tracking service
  }
});

// Monitor Segment availability
setInterval(function() {
  if (typeof analytics === 'undefined' || !analytics.initialized) {
    console.error('Segment not available');
    // Alert monitoring service
  }
}, 60000); // Check every minute

Testing Checklist

  • Segment Analytics.js loaded successfully
  • Write key is correct
  • Page views tracking
  • Custom events tracking
  • User identification working
  • Traits being set correctly
  • Group analytics working (if used)
  • Destinations receiving data
  • No console errors
  • Events appearing in Debugger
  • Data in downstream destinations