Back to all functions

Segment: Send Identify Event

Function to send out a Identify event to Segment. Identify lets you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about them. Segment recommends calling Identify a single time when the user’s account is first created, and only identifying again later when their traits change or wen you capture more information about them.

Created By
Muhammad Dabeer
Community
download-icon
INPUT VARIABLES
{
userId
}
Unique identifier for the user in your database.
{
traits
}
Free-form dictionary of traits of the user, like email or name.
{
writeKey
}
Your Segment writeKey
{
}
{
}
{
}
share-icon
OUTPUT VARIABLES
{
response
}
JSON Stringified response from the API call
{
}
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
success
}
Event tracked successfully
{
success
}
Event tracked successfully
{
}
{
}
{
}
{
}

Function Walkthrough

Function Code Snippet

 
export default async function main(args) {
  let { writeKey, userId, traits } = args.inputVars; // Input variables

  // Check if the user has inputted the required variables
  if (!writeKey || !userId || !traits) {
    return {
      // Returns the error path so we can continue the design
      next: { path: 'error' },
      // Renders a debug message in Voiceflow
      trace: [{ type: "debug", payload: { message: "Missing required input variables for this function" } }]
    };
  }
  
  function base64Encode(str) {
    const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    let output = '';
 
    for (let i = 0; i < str.length; i += 3) {
      const byte1 = str.charCodeAt(i) & 0xFF;
      const byte2 = i + 1 < str.length ? str.charCodeAt(i + 1) & 0xFF : 0;
      const byte3 = i + 2 < str.length ? str.charCodeAt(i + 2) & 0xFF : 0;
 
      const enc1 = byte1 >> 2;
      const enc2 = ((byte1 & 0x3) << 4) | (byte2 >> 4);
      const enc3 = ((byte2 & 0xF) << 2) | (byte3 >> 6);
      const enc4 = byte3 & 0x3F;
 
      if (isNaN(byte2)) {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + '==';
      } else if (isNaN(byte3)) {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + charSet.charAt(enc3) + '=';
      } else {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + charSet.charAt(enc3) + charSet.charAt(enc4);
      }
    }
 
    return output;
  }
  
  
  // Base URL for sending data to Segment
  const url = 'https://api.segment.io/v1/identify';

  // Create the data payload
  const payload = {
    type: "identify",
    userId: userId,
    traits: traits
  };


  // Setup the request options, including headers
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${base64Encode(writeKey + ':')}`
    },
    body: JSON.stringify(payload)
  };

  // This is where we made the fetch request, we use try-catch for error handling
  try {
    // Make the fetch request
    const response = await fetch(url, config);
    // Parse the response
    const responseBody = await response.json;
    // Check if the response status is OK (status in the range 200-299)
    if (!response.ok) {
      // If not OK, throw an error to be caught by the catch block
      throw new Error(`HTTP error! status: ${response.status}, Message: ${responseBody.message}`);
    }



    // Create the return objects if this is successful
    return {
      // Map the success path so we can continue in our flow
      next: { path: 'success' },
      // Optionally, return the response body if needed
      outputVars: {
        response: JSON.stringify(responseBody)
      }
    };
  }
  // Catches all the errors we threw and displays the debug message
  catch (error) {
    return {
      // Maps the error path so we can continue in our design
      next: { path: 'error' },
      // Renders a debug message in Voiceflow with the error
      trace: [{ type: "debug", payload: { message: "Error:" + error.message + ' ' + url } }]
    };
  }
}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.