Skip to main content

How to Set Up Segment for Customer Data Collection

·APIScout Team
segmentcustomer dataanalyticstutorialapi integration

How to Set Up Segment for Customer Data Collection

Segment is the customer data pipeline. Track events once, send them everywhere — analytics, marketing, data warehouse, CRM. Instead of integrating 10 tools separately, integrate Segment once and route data to all of them.

What You'll Build

  • Event tracking (page views, clicks, conversions)
  • User identification across sessions
  • Data routing to multiple destinations
  • Server-side tracking for sensitive events
  • Custom traits and user profiles

Prerequisites: React/Next.js, Segment account (free: 1,000 visitors/month).

1. Setup

Create Source

  1. Sign up at segment.com
  2. Add a Source → JavaScript (Website)
  3. Copy your Write Key

Install

npm install @segment/analytics-next

Initialize

// lib/segment.ts
import { AnalyticsBrowser } from '@segment/analytics-next';

export const analytics = AnalyticsBrowser.load({
  writeKey: process.env.NEXT_PUBLIC_SEGMENT_WRITE_KEY!,
});

Provider Component

// app/providers.tsx
'use client';
import { useEffect } from 'react';
import { analytics } from '@/lib/segment';
import { usePathname } from 'next/navigation';

export function SegmentProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();

  useEffect(() => {
    analytics.page(); // Track page view
  }, [pathname]);

  return <>{children}</>;
}

2. Core Methods

Page Tracking

// Automatic page tracking (in provider above)
analytics.page();

// With properties
analytics.page('Pricing', {
  plan_shown: 'pro',
  ab_test: 'pricing-v2',
});

Event Tracking

// Track a custom event
analytics.track('Button Clicked', {
  button_name: 'Start Free Trial',
  page: 'pricing',
  plan: 'pro',
});

// Track a purchase
analytics.track('Purchase Completed', {
  revenue: 29.00,
  currency: 'USD',
  plan: 'pro',
  billing_period: 'monthly',
});

// Track feature usage
analytics.track('Feature Used', {
  feature: 'api_dashboard',
  action: 'export_data',
  format: 'csv',
});

User Identification

// After login — link anonymous activity to known user
analytics.identify(user.id, {
  email: user.email,
  name: user.name,
  plan: user.plan,
  company: user.company,
  createdAt: user.createdAt,
});

// After logout — reset identity
analytics.reset();

Group (Company/Team)

// Associate user with a company (B2B)
analytics.group(company.id, {
  name: company.name,
  plan: company.plan,
  employees: company.employeeCount,
  industry: company.industry,
});

3. Tracking Plan

Define what events to track before instrumenting:

EventPropertiesTrigger
Page Viewedpath, referrer, titleEvery page load
Sign Up Startedmethod (email, google)Sign-up form shown
Sign Up Completedmethod, planAccount created
LoginmethodUser logs in
Feature Usedfeature_name, actionKey feature interactions
Plan Selectedplan_name, price, periodPricing page selection
Checkout Startedplan, amountPayment form shown
Purchase Completedrevenue, plan, currencyPayment successful
Subscription Cancelledplan, reason, days_activeUser cancels

Event Naming Conventions

✅ Object + Action (past tense): "Purchase Completed", "Feature Used"
❌ Verb + Object: "Completed Purchase", "Used Feature"
❌ camelCase: "purchaseCompleted"
❌ snake_case: "purchase_completed"

4. Server-Side Tracking

For events that shouldn't be tracked client-side (revenue, sensitive data):

npm install analytics-node  # Or @segment/analytics-node
// lib/segment-server.ts
import { Analytics } from '@segment/analytics-node';

export const analyticsServer = new Analytics({
  writeKey: process.env.SEGMENT_WRITE_KEY!,
});

// Track server-side event
analyticsServer.track({
  userId: user.id,
  event: 'Subscription Created',
  properties: {
    plan: 'pro',
    amount: 2900,
    currency: 'usd',
    mrr: 29.00,
  },
});

// Identify from server
analyticsServer.identify({
  userId: user.id,
  traits: {
    email: user.email,
    plan: 'pro',
    lifetime_value: 348.00,
  },
});

5. Connect Destinations

In Segment Dashboard → Destinations, add tools:

DestinationPurposeData Sent
Google Analytics 4Web analyticsPage views, events
MixpanelProduct analyticsEvents, user profiles
AmplitudeProduct analyticsEvents, user properties
HubSpotCRMIdentify calls, events
IntercomCustomer messagingIdentify, track
BigQueryData warehouseAll events (raw)
SlackNotificationsFiltered events
BrazeMarketing automationEvents, user traits

Destination Filters

Only send relevant events to each destination:

Google Analytics ← All events
Mixpanel ← Product events only (exclude marketing events)
HubSpot ← Identify calls + Purchase events only
BigQuery ← Everything (raw data lake)
Slack ← Purchase events only (revenue notifications)

6. Debugging

Segment Debugger

In Segment Dashboard → Sources → Your Source → Debugger:

  • See events in real time
  • Verify properties are correct
  • Check which destinations received each event

Local Development

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

// Events log to console instead of sending to Segment

Pricing

PlanVisitors/MonthPrice
Free1,000$0
Team10,000$120/month
BusinessCustomCustom

"Visitors" = unique users tracked per month (not events).

Common Mistakes

MistakeImpactFix
Tracking everythingNoise, high costsDefine a tracking plan first (15-20 events max)
Inconsistent event namesCan't query dataUse "Object Action" format consistently
Not calling identify()Can't connect pre/post-loginIdentify after every login
Client-side only trackingMissed server events, unreliable revenueUse server-side for important events
No tracking plan documentationNew devs add random eventsDocument events in a spreadsheet/wiki
Sending PII to all destinationsPrivacy violationsUse destination filters to control data flow

Building your data stack? Compare Segment vs PostHog vs Rudderstack on APIScout — customer data platforms compared.

Comments