SDKs overview

Segment offers a suite of Software Development Kits (SDKs) and client libraries designed to facilitate the collection and routing of customer data to its platform. These SDKs abstract the underlying API interactions, providing developers with language-specific methods to track user behavior, identify users, and manage user traits across various applications and devices. The primary goal of these libraries is to ensure consistent and reliable data capture, which is then processed by Segment and forwarded to configured destinations, such as analytics tools, marketing automation platforms, and data warehouses.

The SDKs are categorized into client-side and server-side implementations. Client-side SDKs, such as those for JavaScript, iOS, and Android, are embedded directly within user-facing applications. They automatically capture events like page views, screen views, and user interactions, often with built-in mechanisms for managing user sessions and offline data storage. Server-side SDKs, including those for Node.js, Python, and Go, are used in backend services to track events that occur server-side, such as order fulfillment or database updates, where direct client interaction is not present or appropriate. This dual approach allows for comprehensive data collection across the entire customer journey, from initial website visits to complex backend processes.

Segment's SDKs adhere to a consistent API surface, typically exposing methods like track for recording actions, identify for associating user properties, page/screen for view tracking, and group for managing organizational units. This standardization simplifies development and ensures data consistency across different platforms and programming languages. For detailed technical specifications and method signatures, developers can refer to the Segment API reference documentation.

Official SDKs by language

Segment maintains a range of official SDKs for popular programming languages and platforms, ensuring robust and supported integrations. These SDKs are actively developed and provide the most reliable way to integrate with Segment's platform. The table below outlines the primary official SDKs, their corresponding packages, installation commands, and general maturity status.

Language/Platform Package/Library Installation Command Maturity
JavaScript (Web) analytics.js <script> tag or npm install @segment/analytics-next Stable
Node.js (Server) @segment/analytics-node npm install @segment/analytics-node Stable
Python (Server) segment-python pip install segment-python Stable
Ruby (Server) segment-ruby gem install segment-ruby Stable
Go (Server) segment-go go get github.com/segmentio/go-analytics Stable
PHP (Server) segment/analytics-php composer require segment/analytics-php Stable
Java (Server) analytics-java Maven/Gradle dependency (e.g., com.segment.analytics:analytics:LATEST) Stable
Android (Mobile) analytics-android Gradle dependency (e.g., com.segment.analytics.android:analytics:LATEST) Stable
iOS (Mobile) Analytics CocoaPods (pod 'Segment') or Swift Package Manager Stable
React Native (Mobile) @segment/analytics-react-native npm install @segment/analytics-react-native Stable
Flutter (Mobile) analytics_flutter flutter pub add analytics_flutter Stable
R (Server/Data Science) segment install.packages("segment") Community/Maintained
Elixir (Server) segment Hex package ({:segment, "~> x.x"}) Community/Maintained
C# (Server) Segment.Analytics.CSharp dotnet add package Segment.Analytics.CSharp Stable
Unity (Game Dev) analytics-unity Unity Package Manager (UPM) or Asset Store Stable

For the most current versions and detailed installation instructions, developers should always consult the Segment documentation on libraries.

Installation

The installation process for Segment SDKs varies depending on the programming language and platform. Generally, it involves adding the Segment library as a dependency to your project and then initializing it with your Segment Write Key. The Write Key is unique to each Segment Source and is essential for authenticating your data submissions.

Web (JavaScript)

For web applications, the primary method involves embedding a small JavaScript snippet into the <head> section of your HTML. This snippet asynchronously loads analytics.js, Segment's client-side JavaScript library.

<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=["track","identify","group","page","screen","alias","ready","reset","getAnonymousId","setAnonymousId","addSourceMiddleware","addIntegrationMiddleware","addDestinationMiddleware","setBufferDuration","start","stop","is =Enabled","setSdkWithConfiguration"],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._writeKey=key;analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.13.0";
  analytics.load("YOUR_WRITE_KEY");
  analytics.page();
  }}();
</script>

Replace "YOUR_WRITE_KEY" with your actual Write Key, which can be found in your Segment workspace under Sources. This snippet ensures that Segment's tracking is initiated as soon as possible when a page loads. Alternatively, for modern JavaScript projects using module bundlers, you can install @segment/analytics-next via npm or yarn and initialize it programmatically.

Server-side (Node.js example)

For server-side applications, installation typically involves using a package manager specific to the language. For Node.js, this means npm:

npm install @segment/analytics-node

After installation, you can initialize the client in your application code:

const { Analytics } = require('@segment/analytics-node');

const analytics = new Analytics({
  writeKey: 'YOUR_WRITE_KEY',
  // Optional: configure other settings like flush interval, max queue size
  flushInterval: 10000, // 10 seconds
  maxQueueSize: 1000,
});

analy = analytics;

This setup allows your server to send events to Segment. The flushInterval and maxQueueSize parameters are crucial for managing event buffering and ensuring efficient data transmission, particularly in high-volume environments. For more detailed guides on specific server-side languages, consult the Segment server-side library documentation.

Quickstart example

This example demonstrates a basic implementation of Segment's JavaScript SDK to track a page view and an identified user event on a website. This covers the two most fundamental operations: identifying who the user is and what actions they are taking.

JavaScript (Web)

After embedding the analytics.js snippet as described in the installation section, you can start tracking events. This example shows how to track a user signing up and then viewing a product page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Page</title>
    <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=["track","identify","group","page","screen","alias","ready","reset","getAnonymousId","setAnonymousId","addSourceMiddleware","addIntegrationMiddleware","addDestinationMiddleware","setBufferDuration","start","stop","isEnabled","setSdkWithConfiguration"],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._writeKey=key;analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.13.0";
        analytics.load("YOUR_WRITE_KEY"); // Replace with your actual Write Key
        analytics.page(); // Tracks an initial page view on load
        }}();
    </script>
</head>
<body>
    <h1>Welcome to Our Product!</h1>
    <p>This is a sample product page.</p>

    <button id="signupButton">Sign Up Now</button>

    <script>
        document.getElementById('signupButton').addEventListener('click', function() {
            // Identify the user when they sign up
            analytics.identify('user-123', {
                name: 'John Doe',
                email: '[email protected]',
                plan: 'premium'
            });

            // Track a custom event for signup completion
            analytics.track('Signed Up', {
                method: 'email',
                plan: 'premium'
            });

            alert('Signed up successfully!');
        });

        // Track a specific product view event after initial page load
        analytics.track('Product Viewed', {
            productId: 'prod-abc-123',
            productName: 'Example Widget',
            category: 'Electronics',
            price: 99.99
        });
    </script>
</body>
</html>

In this example:

  • analytics.load("YOUR_WRITE_KEY") initializes the Segment library with your source's unique key.
  • analytics.page() sends a page view event. This is often called once on every page load to track navigation.
  • analytics.identify('user-123', { ... }) associates a unique ID ('user-123') with user traits like name, email, and plan. Once identified, all subsequent events from this user will be linked to these traits.
  • analytics.track('Signed Up', { ... }) sends a custom event named 'Signed Up' with additional properties describing the event, such as the signup method and plan.
  • A second analytics.track('Product Viewed', { ... }) demonstrates tracking a specific item view, providing context about what the user is interacting with.

This structure allows for granular tracking of user actions and properties, forming the foundation of a comprehensive customer data profile within Segment. More advanced usage might involve setting up middleware for data transformation or using specific plugins for A/B testing or advertising platforms, as detailed in the Segment JavaScript SDK documentation.

Community libraries

While Segment provides a robust set of official SDKs, the broader developer community has also contributed various libraries and integrations. These community-driven projects often extend Segment's functionality to less common languages, frameworks, or specific use cases not covered by official offerings. They can range from full-featured client libraries to small utilities that simplify integration or add specific features.

Examples of community contributions might include:

  • Wrappers for niche frameworks: Libraries that integrate Segment's core logic into domain-specific frameworks, simplifying data collection within those ecosystems.
  • Language-specific implementations: SDKs for languages where an official Segment library might not exist or is less mature, such as certain functional programming languages or less common backend technologies.
  • Plugins and middleware: Extensions that add specific data processing capabilities, integrate with third-party services before data reaches Segment, or enhance local debugging.

Developers considering community libraries should evaluate their maintenance status, documentation, and the level of support provided by their creators. While they can offer flexibility, official SDKs generally provide greater stability, security assurances, and direct support from Segment. Resources like GitHub and public package repositories (e.g., npm, PyPI) are common places to discover such community projects. For instance, a search for "Segment" on a platform like GitHub's Segment organization often reveals both official and community-contributed repositories that interact with the Segment ecosystem.

It's also worth noting that the Cloud Native Computing Foundation (CNCF), while not directly related to Segment's SDKs, promotes open-source projects and standards, which aligns with the spirit of community contributions in the broader API and data ecosystem. The availability of diverse SDKs, both official and community-driven, is a common characteristic of mature data platforms, reflecting their adaptability to various development environments and preferences.