Integrating Segment with Usermaven
Segment
Usermaven effortlessly connects with Segment, a Customer Data Platform (CDP), allowing you to track event data and send it to different destinations. This dynamic pairing not only simplifies event tracking but also opens avenues for strategic data utilization. Setting up Usermaven with Segment is a breeze, requiring just a few clicks for seamless integration.
How the Usermaven integration works with segment
How Segment works is that you seamlessly integrate it into your application to commence data collection. This integration extends across various platforms, allowing you to add Segment to your website, mobile apps, servers, or cloud applications. When a customer/user engages with any of your sources, e.g., your website, Segment captures the data and directs it to a specified destination. Destinations are tools for things like ads, email marketing, and analytics. Usermaven is one such analytics tool. Segment servers retain an archived copy of the data and send it to the destination i.e. Usermaven.
This seamless data flow ensures not only real-time insights but also empowers your long-term analytics strategy by providing a consolidated repository of historical user interactions.
This is how it works:
-
Access the Segment web app and navigate to the "Catalog" section.
-
Within the Catalog, select "Destinations."
-
Utilize the search function to locate "Usermaven" in the Destinations Catalog, and choose the Usermaven destination.
-
Click on "Configure Usermaven" to initiate the configuration process.
-
Choose an existing Source from your Segment account to establish a connection with Usermaven, specifically under the "Actions" category.
-
Open the Usermaven App and proceed to "Workspace Settings" > "General Settings."
-
Copy the API Key provided in the Usermaven workspace settings.
-
Return to the Segment web app and navigate to the settings for the "Usermaven (Actions)" destination.
-
Paste the copied API Key into the designated field within the "Usermaven (Actions)" destination settings in Segment.
By following these steps, you'll seamlessly configure the Usermaven destination in Segment, ensuring a smooth integration process.
Server side tracking with segment for Usermaven
Seamless Server-Side Tracking with Segment involves crucial steps to effectively piece together user activities. Here’s what you need to know:
-
Anonymous ID Variability : When handling events through server-side tracking such as the Segment PHP SDK, it's imperative to note that the anonymous ID can exhibit variability. This variance may lead to discrepancies in stitching together the user timeline accurately.
-
IP Address Transmission : The transmission of IP addresses in server-side tracking utilizes the server's IP address. Consequently, the user's location may not reflect their original location but rather the location of the server's IP.
Resolution for anonymous IDs:
Handling anonymous IDs is crucial for accurately tracking user interactions and behaviors across your marketing platforms. Varying anonymous IDs can lead to fragmented user data, making it challenging to gain comprehensive insights. To ensure consistency and reliability in tracking, it's essential to retrieve and manage the anonymous ID effectively. This section provides an in-depth guide on resolving issues related to anonymous IDs, incorporating best practices for both frontend and backend implementations.
Overview
Anonymous IDs serve as unique identifiers for users who have not yet authenticated or registered on your platform. By consistently tracking these IDs, you can:
- Maintain User Continuity: Track user interactions across multiple sessions and devices.
- Enhance Personalization: Deliver personalized experiences based on user behavior.
- Improve Data Accuracy: Ensure that user data is accurately attributed, avoiding duplication or fragmentation.
Retrieving anonymous IDs from cookies
To address the issue of varying anonymous IDs, follow these steps:
- Set Up the Usermaven Tracking Script: Ensure that the Usermaven tracking script is correctly integrated into your marketing website. This script is responsible for setting the anonymous ID in the browser's cookies.
- Retrieve the Anonymous ID from Cookies: Use JavaScript to extract the anonymous ID from the cookies. The cookie name follows the pattern
__eventn_id_{API_KEY}
, where{API_KEY}
is your workspace's API key. - Include the Anonymous ID in Service Calls: When making service calls (e.g., using Axios or Fetch), include the retrieved anonymous ID either in the request headers or as part of the request payload.
Example implementation
Below are detailed examples demonstrating how to implement the retrieval and usage of anonymous IDs both on the frontend and backend.
Frontend Implementation (JavaScript)
// Your workspace API key
const API_KEY = 'UMWf7XBWPT';
// Function to get the cookie value by its name
function getCookieValue(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
// Function to send a request with the anonymous ID from the cookie
function sendRequestWithAnonymousId(url, requestData) {
const cookieName = `__eventn_id_${API_KEY}`;
const anonymousId = getCookieValue(cookieName);
if (!anonymousId) {
console.warn(`Anonymous ID cookie (${cookieName}) not found.`);
// Optionally, handle the absence of anonymous ID (e.g., generate a new one)
}
// Adding the anonymous ID as a header or part of the request
axios.post(url, requestData, {
headers: {
'Anonymous-Id': anonymousId
}
})
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
}
// Example usage
const exampleUrl = 'https://api.yourservice.com/endpoint';
const exampleData = {
// Your request payload
};
sendRequestWithAnonymousId(exampleUrl, exampleData);
Explanation:
- API Key Integration: The
API_KEY
constant holds your workspace's API key (UMWf7XBWPT
). This key is used to construct the cookie name from which the anonymous ID is retrieved. - Cookie Retrieval: The
getCookieValue
function searches for the cookie named__eventn_id_UMWf7XBWPT
and returns its value. If the cookie is not found, it returnsnull
. - Request Handling: The
sendRequestWithAnonymousId
function sends a POST request to the specified URL, including the anonymous ID in the request headers. It also includes error handling to manage scenarios where the anonymous ID is missing or the request fails.
Backend Implementation (PHP)
<?php
require_once('vendor/autoload.php');
use Segment\Segment;
// Your workspace API key
define('API_KEY', 'UMWf7XBWPT');
// Initialize Segment with your write key
Segment::init('YOUR_WRITE_KEY');
/**
* Function to get the anonymous ID from headers
*
* @return string|null
*/
function getAnonymousIdFromHeaders() {
// Retrieve all HTTP headers
$headers = getallheaders();
// Construct the expected header name
$headerName = 'Anonymous-Id';
// Check if the Anonymous-Id header exists
if (isset($headers[$headerName])) {
return $headers[$headerName];
}
return null;
}
/**
* Function to handle incoming requests and track events
*/
function handleRequest() {
// Get the anonymous ID from headers
$anonymousId = getAnonymousIdFromHeaders();
if (!$anonymousId) {
error_log('Anonymous ID not provided in the request headers.');
// Optionally, handle the absence of anonymous ID (e.g., respond with an error)
return;
}
// Example user ID, replace with actual user ID if available
$userId = 'userId123';
// Track an event with Segment
Segment::track([
"userId" => $userId, // Replace with actual user ID if available
"event" => "Event Name",
"properties" => [
"property1" => "value1",
"property2" => "value2"
],
"context" => [
"anonymousId" => $anonymousId,
"library" => [
"name" => "your-library-name",
"version" => "1.0.0"
],
"app" => [
"name" => "Your App Name",
"version" => "1.0.0"
]
]
]);
// Flush the data to Segment
Segment::flush();
}
// Handle the incoming request
handleRequest();
?>
Explanation:
- API Key Definition: The
API_KEY
constant holds your workspace's API key (UMWf7XBWPT
). While it's defined here for completeness, it's primarily used on the frontend to construct the cookie name. On the backend, ensure that sensitive information like API keys is securely managed and not exposed. - Segment Initialization: Replace
'YOUR_WRITE_KEY'
with your actual Segment write key. This key authenticates your server with Segment to send event data. - Header Retrieval: The
getAnonymousIdFromHeaders
function retrieves theAnonymous-Id
from the incoming request headers. If the header is missing, it logs an error and can optionally handle the scenario accordingly. - Event Tracking: The
handleRequest
function tracks an event using Segment'strack
method, including theanonymousId
in the context. Additional context such as library and app information can be included to enrich the event data. - Data Flushing: The
Segment::flush()
method ensures that all queued data is sent to Segment. It's essential to call this method to prevent data loss.
Resolution for the IP address issue:
To handle the issue of IP address discrepancies, in Laravel, you can pass the client's IP address to Segment using the analytics-php SDK. Extract the IP address from the Laravel request and include it in the event's context, as shown in the example code snippet:
use Segment\Segment;
// Initialize Segment with your write key
Segment::init('YOUR_WRITE_KEY');
// Get the client's IP address using Laravel's request helper
$clientIpAddress = request()->ip();
// Send an event to Segment with the client IP address
Segment::track([
"userId" => "userId123", // replace with actual user ID if available
"event" => "Event Name",
"properties" => [
"property1" => "value1",
"property2" => "value2"
],
"context" => [
"ip" => $clientIpAddress
]
]);
// Flush the data to Segment
Segment::flush();
By implementing these solutions, you can ensure the correct transmission of data to Segment and Usermaven, resolving the identified issues. This approach guarantees accurate attribution when utilizing the Attribution report.
Additionally, you can enhance your data insights by populating the context object with additional information, as outlined in the Segment documentation. Key details such as Referrer, User Agent, locale, and more can be included. Refer to the Segment documentation here: Segment Docs - Context Object. (opens in a new tab)