Skip to main content

Set Up Segment for Customer Data in 2026

·APIScout Team
Share:

Set Up Segment for Customer Data in 2026

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.

TL;DR

  • Segment is a Customer Data Platform (CDP) — instrument your app once and route behavioral data to any analytics, marketing, or data warehouse tool without code changes
  • Use the verb-noun naming convention for events: "Order Completed", "Feature Used", "Subscription Cancelled" — consistent naming is the difference between useful data and chaos
  • Track server-side for revenue and subscription events — client-side tracking is unreliable for high-value conversions
  • Destination filters prevent sending all events to all tools — your CRM doesn't need page view events, your data warehouse needs everything
  • The free tier (1,000 monthly tracked users) is enough to validate your tracking plan before committing to a paid plan

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

The CDP Value Proposition

Understanding what a Customer Data Platform actually solves makes it easier to decide when to use one. Before CDPs, instrumenting analytics meant integrating each tool's SDK directly into your application. Adding Amplitude meant installing the Amplitude SDK. Adding a CRM integration meant installing the CRM SDK. Each SDK loaded separately, tracked events independently, and maintained its own user identity model. When you wanted to stop using a tool, you had to remove its SDK and all its tracking calls from your codebase.

The CDP pattern breaks this coupling. You instrument your application with a single analytics call (Segment's track, identify, page) and Segment routes that data to every destination. Adding a new tool means enabling it in the Segment dashboard — no code deployment. Removing a tool means disabling it — no code changes. Your application code becomes independent of the specific analytics and marketing tools you use, which matters enormously when those tools change year over year as your business needs evolve.

Segment competes primarily with RudderStack and Amplitude CDPs. RudderStack is the open-source alternative — you can self-host it, which eliminates per-MTU costs but adds infrastructure overhead. RudderStack's feature parity with Segment is high; the main reasons to choose RudderStack are cost at scale and data sovereignty requirements. Amplitude's CDP is built around Amplitude's own analytics product and is strongest for teams that want analytics-first workflows, but it has a smaller destination catalog. Segment remains the default choice for breadth of destination integrations (450+) and the depth of its data governance tooling via Segment Protocols.

Event Taxonomy Design

The quality of your analytics data depends almost entirely on event taxonomy decisions made before the first line of tracking code is written. Retrofitting a consistent schema onto inconsistently named events is painful work. Get this right upfront.

The Segment-recommended convention is Object + Action in past tense, with Title Case: "Video Watched", "Report Downloaded", "Team Member Invited". The object is the thing that was acted upon, the action is what happened to it. This convention survives team growth because it's learnable and consistent.

Every event should include a set of standard context properties automatically added by the Segment SDK (userId, anonymousId, timestamp, page URL, browser, OS) and your own standard properties that should appear on every event regardless of type. A good set of standard custom properties includes user_plan (current subscription tier), feature_area (which part of the product this happened in), and experiment_id (if the user is in an A/B test). Adding these to every event means you can always segment any metric by subscription tier or experiment variant without having to re-instrument.

Properties to include consistently regardless of event type are more important than the specific event name. A "Purchase Completed" event is much more useful if it consistently includes revenue, currency, plan_name, and billing_period than if some calls include these and some don't. Document your event schema in a shared tracking plan (a spreadsheet or wiki page) and review it when adding new events.

Destinations in Practice

Connecting Segment to a destination is mostly a configuration exercise in the Segment dashboard, but the practical details of each connection shape how useful the data becomes.

For Amplitude (product analytics), Segment sends events and user properties on every track and identify call. Amplitude maps userId to Amplitude's user identity. The main configuration choice is whether to use Amplitude's cloud destination (data goes to Segment, then to Amplitude) or the device-mode destination (Amplitude SDK loaded directly in the browser, slightly faster). Cloud mode is preferable for privacy compliance because user data flows through fewer client-side scripts.

For Salesforce (CRM), Segment typically maps identify calls to Contact creation/updates and high-value track events (like "Trial Started" or "Purchase Completed") to Activity records or Lead conversion triggers. The Salesforce destination requires mapping Segment traits to Salesforce field names, which takes some setup but is well documented.

For Customer.io (email automation), Segment's identify calls become Customer.io customer records, and track events become events in Customer.io's event-driven automation workflow. This powers email flows like "User hasn't used Feature X in 7 days → send education email" without any direct Customer.io integration code.

Destination filters are underused and important. The default behavior sends every track event to every enabled destination. This creates noise — your CRM doesn't need "Page Viewed" events, your error monitoring tool doesn't need "Button Clicked" events. Filters reduce destination costs (many charge per event received), reduce noise in each tool's data model, and prevent accidentally sending sensitive event properties to tools that don't need them.

Segment Protocols and Schema

Segment Protocols is the data governance layer that enforces event schema consistency. Without it, engineers add new events with slightly different property names, and over time "purchase_completed" and "Purchase Completed" and "PurchaseCompleted" accumulate in your data warehouse as separate events.

Protocols works by defining a JSON Schema for each event type. You specify the required properties, their types, and any allowed values. When an event violates the schema — a required property is missing, a property has the wrong type, an unrecognized event name is used — Protocols flags the violation. Depending on your configuration, violations can be blocked (event dropped), forwarded but flagged, or just logged for review.

The schema is version-controlled and can be managed via the Segment Config API, which means you can enforce event schema in CI/CD. Running schema validation against your tracking code before deployment catches schema violations in development rather than after they've reached production data.

Protocols is a paid feature on Segment's Team and Business plans. For teams at the free or starter tier, the practical alternative is a shared tracking plan document with code review enforcement — less automated, but it establishes the discipline that matters.

Tracking user behavior before obtaining consent is a GDPR violation in the EU and increasingly problematic under CCPA, Brazil's LGPD, and other privacy regulations. Segment does not handle consent collection — that's your responsibility — but it provides the mechanisms to respect consent decisions.

The pattern: show a consent banner before loading the Segment SDK or calling any analytics methods. If the user declines analytics tracking, don't load Segment at all. If they accept, load Segment and call analytics.identify() and tracking as normal.

// Only load analytics after consent
if (userHasConsentedToAnalytics()) {
  const { analytics } = await import('@/lib/segment');
  analytics.identify(userId, traits);
}

For users who later revoke consent (GDPR right to opt out), call analytics.reset() to clear the anonymous identity, stop tracking, and notify your destinations. Segment's Privacy Portal (paid plans) provides user deletion requests that propagate a deletion request to connected destinations, though each destination handles the actual deletion.

For personally identifiable information (PII), the safest approach is to not send PII to Segment at all — use pseudonymous IDs (your internal user ID) in identify() rather than email addresses or names as the userId. Reserve email and name for traits, and use destination filters to control which tools receive those traits. This reduces your exposure when a destination suffers a data breach.

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? Explore analytics and CDP tools on APIScout. Also see our guides on API authentication patterns and building APIs with TypeScript for building the server-side tracking infrastructure.

Related: Building a SaaS Backend, How to Add Product Analytics with PostHog, Build a Real-Time Dashboard with the Mixpanel API

The API Integration Checklist (Free PDF)

Step-by-step checklist: auth setup, rate limit handling, error codes, SDK evaluation, and pricing comparison for 50+ APIs. Used by 200+ developers.

Join 200+ developers. Unsubscribe in one click.