Segment Event Tracking: CDP Integration | OpsBlu Docs

Segment Event Tracking: CDP Integration

How to implement Segment event tracking to route data across analytics destinations. Covers analytics.track(), identify(), Protocols schema...

Overview

Segment is a Customer Data Platform (CDP) that acts as a single hub for collecting, cleaning, and routing your customer data to hundreds of tools. Rather than implementing tracking for each analytics tool separately, you implement Segment once, and it forwards your data to all your connected destinations (Google Analytics, Mixpanel, Amplitude, Salesforce, etc.).

Think of Segment as the "central nervous system" for your customer data. You send events to Segment using their unified API, and Segment handles the complexity of transforming and sending that data to each of your downstream tools. This dramatically simplifies implementation, ensures data consistency, and makes it easy to add or remove tools without code changes.

Event Model

How Segment Events Work

Segment uses a simple, standardized event model based on four core API calls:

  1. Track: Record user actions (clicks, purchases, signups)
  2. Identify: Set user traits/properties
  3. Page: Record pageviews
  4. Screen: Record screen views (mobile apps)

Event Structure:

{
  "type": "track",
  "event": "Product Purchased",
  "userId": "user_12345",
  "properties": {
    "product_id": "SKU_789",
    "price": 49.99,
    "currency": "USD"
  },
  "timestamp": "2024-01-15T10:30:00Z",
  "context": {
    "ip": "192.168.1.1",
    "userAgent": "Mozilla/5.0...",
    "page": {
      "url": "https://example.com/checkout"
    }
  }
}

Key Concepts

  • Sources: Where data comes from (website, mobile app, server)
  • Destinations: Where data goes (analytics, marketing, data warehouses)
  • Events: User actions tracked via track() calls
  • Traits: User attributes set via identify() calls
  • Spec: Standardized event naming conventions
  • Transformations: Modify data before sending to destinations

Limits

  • Event name: 255 characters
  • Property name: 255 characters
  • Property value: No hard limit (reasonable sizes)
  • Events per second: Based on plan (hundreds to thousands)
  • Destinations: Unlimited on most plans
  • Sources: Based on plan

Standard Events

Segment provides a Semantic Events Spec with standardized event names and properties for common actions.

Ecommerce Spec

Segment has detailed specifications for ecommerce tracking:

Product Viewed:

analytics.track('Product Viewed', {
  product_id: 'SKU_12345',
  name: 'Wireless Mouse',
  category: 'Electronics',
  brand: 'Logitech',
  price: 29.99,
  currency: 'USD',
  url: 'https://example.com/products/mouse',
  image_url: 'https://example.com/images/mouse.jpg'
});

Product Added:

analytics.track('Product Added', {
  product_id: 'SKU_12345',
  name: 'Wireless Mouse',
  price: 29.99,
  quantity: 1,
  cart_id: 'cart_abc123'
});

Checkout Started:

analytics.track('Checkout Started', {
  order_id: 'ORDER_123',
  value: 99.97,
  revenue: 99.97,
  shipping: 10.00,
  tax: 8.00,
  currency: 'USD',
  products: [
    {
      product_id: 'SKU_12345',
      name: 'Wireless Mouse',
      price: 29.99,
      quantity: 2
    }
  ]
});

Order Completed:

analytics.track('Order Completed', {
  order_id: 'ORDER_123',
  total: 117.97,
  revenue: 99.97,
  shipping: 10.00,
  tax: 8.00,
  discount: 10.00,
  coupon: 'SAVE10',
  currency: 'USD',
  products: [
    {
      product_id: 'SKU_12345',
      sku: 'SKU_12345',
      name: 'Wireless Mouse',
      price: 29.99,
      quantity: 2,
      category: 'Electronics'
    }
  ]
});

Lifecycle Events

Signed Up:

analytics.track('Signed Up', {
  method: 'Email',
  plan: 'Trial',
  referrer: 'Google Ad'
});

Account Created:

analytics.track('Account Created', {
  account_id: 'ACC_123',
  account_name: 'Acme Corp',
  plan: 'Enterprise'
});

Video Spec

Video Playback Started:

analytics.track('Video Playback Started', {
  session_id: 'session_123',
  content_asset_id: 'vid_456',
  title: 'Product Demo',
  duration: 180,
  livestream: false
});

Custom Events

While Segment's spec events are recommended, you can track any custom event.

Track API

JavaScript:

// Basic event
analytics.track('Button Clicked');

// Event with properties
analytics.track('Feature Used', {
  feature_name: 'Export Data',
  file_format: 'CSV',
  record_count: 1000
});

// Event with all options
analytics.track('Video Watched', {
  video_id: 'vid_123',
  title: 'Tutorial',
  duration: 180,
  completion_percent: 75
}, {
  context: {
    campaign: {
      name: 'Spring Sale',
      source: 'email'
    }
  },
  integrations: {
    'Google Analytics': true,
    'Mixpanel': false  // Don't send to Mixpanel
  }
});

Python:

from segment import analytics

analytics.write_key = 'YOUR_WRITE_KEY'

# Track event
analytics.track(
    user_id='user_12345',
    event='API Request',
    properties={
        'endpoint': '/api/users',
        'method': 'GET',
        'response_time_ms': 45
    }
)

Node.js:

const Analytics = require('analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY');

// Track event
analytics.track({
  userId: 'user_12345',
  event: 'Email Sent',
  properties: {
    subject: 'Welcome!',
    template: 'onboarding_day_1',
    recipient_count: 1
  }
});

Event Naming Best Practices

Use Spec Events When Possible:

// Good - uses spec
analytics.track('Product Viewed', { ... });
analytics.track('Order Completed', { ... });

// Avoid - custom when spec exists
analytics.track('User Bought Product', { ... });

Object-Action Format:

// Good
analytics.track('Article Shared');
analytics.track('Report Downloaded');
analytics.track('Account Upgraded');

// Avoid
analytics.track('Share Article');
analytics.track('Download');

Ecommerce Events

Segment's ecommerce spec provides complete tracking for online stores.

Full Ecommerce Flow

1. Product Browsing:

// Product list viewed
analytics.track('Product List Viewed', {
  list_id: 'search_results',
  category: 'Electronics',
  products: [
    {
      product_id: 'SKU_123',
      name: 'Wireless Mouse',
      price: 29.99
    },
    {
      product_id: 'SKU_456',
      name: 'Keyboard',
      price: 79.99
    }
  ]
});

// Product clicked
analytics.track('Product Clicked', {
  product_id: 'SKU_123',
  name: 'Wireless Mouse',
  price: 29.99,
  position: 1
});

// Product viewed
analytics.track('Product Viewed', {
  product_id: 'SKU_123',
  name: 'Wireless Mouse',
  category: 'Electronics',
  brand: 'Logitech',
  price: 29.99,
  currency: 'USD'
});

2. Cart Management:

// Product added to cart
analytics.track('Product Added', {
  cart_id: 'cart_abc',
  product_id: 'SKU_123',
  name: 'Wireless Mouse',
  price: 29.99,
  quantity: 1
});

// Cart viewed
analytics.track('Cart Viewed', {
  cart_id: 'cart_abc',
  products: [
    {
      product_id: 'SKU_123',
      name: 'Wireless Mouse',
      price: 29.99,
      quantity: 2
    }
  ]
});

// Product removed from cart
analytics.track('Product Removed', {
  cart_id: 'cart_abc',
  product_id: 'SKU_123',
  name: 'Wireless Mouse',
  quantity: 1
});

3. Checkout:

// Checkout started
analytics.track('Checkout Started', {
  order_id: 'ORDER_123',
  value: 59.98,
  revenue: 59.98,
  products: [...]
});

// Checkout step completed
analytics.track('Checkout Step Completed', {
  checkout_id: 'checkout_123',
  step: 2,
  step_name: 'Shipping Info',
  shipping_method: 'Standard'
});

// Payment info entered
analytics.track('Payment Info Entered', {
  checkout_id: 'checkout_123',
  order_id: 'ORDER_123',
  payment_method: 'Credit Card'
});

// Order completed
analytics.track('Order Completed', {
  order_id: 'ORDER_123',
  total: 77.98,
  revenue: 59.98,
  shipping: 10.00,
  tax: 8.00,
  currency: 'USD',
  products: [...]
});

4. Post-Purchase:

// Order refunded
analytics.track('Order Refunded', {
  order_id: 'ORDER_123',
  total: 77.98,
  currency: 'USD'
});

// Order cancelled
analytics.track('Order Cancelled', {
  order_id: 'ORDER_123',
  reason: 'Customer Request'
});

User Properties

Use the identify() call to set user attributes.

Identify API

JavaScript:

// Identify user with traits
analytics.identify('user_12345', {
  email: 'john@example.com',
  name: 'John Doe',
  plan: 'Premium',
  signup_date: '2024-01-15',
  company: {
    id: 'company_456',
    name: 'Acme Corp',
    plan: 'Enterprise',
    employees: 100
  }
});

// Anonymous identify (set traits before user ID known)
analytics.identify({
  sessionCount: 3,
  lastVisit: new Date()
});

Special Traits:

Segment recognizes specific trait names:

analytics.identify('user_12345', {
  // User Info
  email: 'john@example.com',
  name: 'John Doe',
  firstName: 'John',
  lastName: 'Doe',
  username: 'johndoe',
  phone: '+1-555-123-4567',
  avatar: 'https://example.com/avatar.jpg',

  // Dates
  createdAt: '2024-01-15T10:00:00Z',
  birthday: '1990-05-20',

  // Location
  address: {
    street: '123 Main St',
    city: 'San Francisco',
    state: 'CA',
    postalCode: '94105',
    country: 'US'
  },

  // Company (B2B)
  company: {
    id: 'company_456',
    name: 'Acme Corp',
    industry: 'Technology',
    employee_count: 100,
    plan: 'Enterprise'
  }
});

Python:

analytics.identify(
    user_id='user_12345',
    traits={
        'email': 'john@example.com',
        'name': 'John Doe',
        'plan': 'Premium',
        'total_spent': 499.95
    }
)

Group API (B2B)

For tracking companies/organizations:

// Associate user with group
analytics.group('company_456', {
  name: 'Acme Corp',
  industry: 'Technology',
  employees: 100,
  plan: 'Enterprise',
  mrr: 999.00,
  website: 'https://acme.com'
});

Event Parameters

Event properties provide context about what happened.

Property Best Practices

Follow Spec When Possible:

// Use spec property names
analytics.track('Product Viewed', {
  product_id: 'SKU_123',      // Spec
  name: 'Wireless Mouse',     // Spec
  price: 29.99,               // Spec
  category: 'Electronics',    // Spec
  brand: 'Logitech'          // Spec
});

Consistent Naming:

// Good - consistent snake_case
{
  product_id: 'SKU_123',
  order_id: 'ORDER_456',
  user_tier: 'premium'
}

// Avoid - mixed naming
{
  productId: 'SKU_123',      // camelCase
  order_id: 'ORDER_456',     // snake_case
  UserTier: 'premium'        // PascalCase
}

Context Object

Segment automatically includes context, or you can override:

analytics.track('Event Name', {
  property: 'value'
}, {
  context: {
    ip: '192.168.1.1',
    locale: 'en-US',
    timezone: 'America/Los_Angeles',
    campaign: {
      name: 'Spring Sale',
      source: 'google',
      medium: 'cpc',
      term: 'wireless mouse',
      content: 'ad_variant_a'
    },
    page: {
      path: '/products',
      referrer: 'https://google.com',
      search: '?utm_source=google',
      title: 'Products',
      url: 'https://example.com/products'
    }
  }
});

Integrations Object

Control which destinations receive the event:

analytics.track('Sensitive Event', {
  data: 'value'
}, {
  integrations: {
    'All': false,                    // Disable all
    'Google Analytics': true,        // Enable specific ones
    'Customer.io': true,
    'Mixpanel': {
      revenue: 100  // Pass specific options
    }
  }
});

Implementation Methods

1. Analytics.js (Web)

Installation:

<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>

Usage:

// Page view (automatic on load, or manual for SPA)
analytics.page('Product', 'Details', {
  product_id: 'SKU_123',
  category: 'Electronics'
});

// Identify user
analytics.identify('user_12345', {
  email: 'user@example.com',
  name: 'John Doe'
});

// Track event
analytics.track('Button Clicked', {
  button_name: 'Sign Up',
  location: 'Homepage'
});

2. Server-Side SDKs

Node.js:

const Analytics = require('analytics-node');
const analytics = new Analytics('YOUR_WRITE_KEY', {
  flushAt: 20,
  flushInterval: 10000
});

// Track
analytics.track({
  userId: 'user_12345',
  event: 'Server Event',
  properties: {
    action: 'data_export',
    records: 10000
  }
});

// Identify
analytics.identify({
  userId: 'user_12345',
  traits: {
    email: 'user@example.com',
    plan: 'Enterprise'
  }
});

// Flush events
await analytics.flush();

Python:

import analytics

analytics.write_key = 'YOUR_WRITE_KEY'

# Track
analytics.track(
    user_id='user_12345',
    event='Background Job',
    properties={
        'job_type': 'email_campaign',
        'recipients': 1000
    }
)

# Identify
analytics.identify(
    user_id='user_12345',
    traits={
        'email': 'user@example.com',
        'plan': 'Enterprise'
    }
)

# Flush before exit
analytics.flush()

Ruby:

require 'segment/analytics'

Analytics = Segment::Analytics.new({
  write_key: 'YOUR_WRITE_KEY'
})

# Track
Analytics.track(
  user_id: 'user_12345',
  event: 'Purchase',
  properties: {
    revenue: 149.99,
    product_id: 'SKU_789'
  }
)

# Identify
Analytics.identify(
  user_id: 'user_12345',
  traits: {
    email: 'user@example.com',
    name: 'John Doe'
  }
)

3. Mobile SDKs

iOS (Swift):

import Segment

// Initialize
let configuration = AnalyticsConfiguration(writeKey: "YOUR_WRITE_KEY")
Analytics.setup(with: configuration)

// Track
Analytics.shared().track("Level Completed", properties: [
    "level": 5,
    "score": 9500,
    "time_seconds": 145
])

// Identify
Analytics.shared().identify("user_12345", traits: [
    "email": "user@example.com",
    "name": "John Doe"
])

// Screen
Analytics.shared().screen("Home Screen", properties: [
    "previous_screen": "Onboarding"
])

Android (Kotlin):

import com.segment.analytics.Analytics
import com.segment.analytics.Properties

// Initialize
val analytics = Analytics.Builder(context, "YOUR_WRITE_KEY")
    .build()

// Track
val properties = Properties()
    .putValue("level", 5)
    .putValue("score", 9500)

analytics.track("Level Completed", properties)

// Identify
val traits = Traits()
    .putEmail("user@example.com")
    .putName("John Doe")

analytics.identify("user_12345", traits, null)

// Screen
analytics.screen("Home Screen")

4. HTTP API

curl https://api.segment.io/v1/track \
  -u YOUR_WRITE_KEY: \
  -H 'Content-Type: application/json' \
  -d '{
    "userId": "user_12345",
    "event": "Item Purchased",
    "properties": {
      "revenue": 39.95,
      "product_id": "SKU_123"
    },
    "timestamp": "2024-01-15T10:30:00Z"
  }'

Debugging & Validation

1. Segment Debugger

Real-time event stream viewer:

  1. Go to Sources > [Your Source] > Debugger
  2. Perform actions in your app
  3. See events appear in real-time
  4. Click event to see full payload
  5. Check which destinations received the event

2. Source Health

Monitor data quality:

  1. Go to Sources > [Your Source] > Health
  2. View error rates
  3. See delivery success to destinations
  4. Identify integration issues

3. Browser Console

// Enable debug mode
analytics.debug();

// Track event and see output
analytics.track('Test Event', {test: true});

// Check user ID
console.log(analytics.user().id());

// Check anonymous ID
console.log(analytics.user().anonymousId());

// Check traits
console.log(analytics.user().traits());

4. Network Inspection

DevTools Network Tab:

Filter: api.segment.io
Look for: POST to /v1/t (track) or /v1/p (page)
Status: 200 OK

5. Destination Validation

Check if events reach destinations:

  1. Go to Debugger
  2. Find your event
  3. Click Destinations tab
  4. See which destinations received it
  5. Check for errors or filtering

Best Practices

Use the Spec

Do:

// Use spec events
analytics.track('Product Viewed', { ... });
analytics.track('Order Completed', { ... });
analytics.track('Signed Up', { ... });

Don't:

// Avoid custom when spec exists
analytics.track('User Viewed Product', { ... });
analytics.track('Purchase Made', { ... });

Consistent Implementation

Single Source of Truth:

  • Implement Segment once
  • Let it forward to all tools
  • Maintain consistency across platforms

Avoid:

  • Implementing GA, Mixpanel, Amplitude separately
  • Data inconsistencies between tools
  • Multiple tracking implementations

Event Volume

  • Be mindful of MTU (Monthly Tracked Users) limits
  • Batch events server-side when possible
  • Don't track on every mousemove/scroll
  • Sample high-volume events if needed

Privacy & Compliance

// Respect user consent
if (userConsentedToTracking) {
  analytics.load('YOUR_WRITE_KEY');
}

// Delete user data (GDPR)
// Use Segment's Privacy Portal or API

// Disable specific destinations
analytics.track('Event', {}, {
  integrations: {
    'Google Analytics': !userOptedOutOfGA
  }
});

Data Quality

  • Use Schema validation (Protocols)
  • Implement Tracking Plans
  • Review events in Debugger regularly
  • Monitor Source Health
  • Set up alerts for errors

Organization

  • Document your tracking plan
  • Use consistent naming conventions
  • Follow spec when possible
  • Create reusable tracking functions
  • Governance for new events

Additional Resources: