AtlasCustomer PortalGo to Atlas

No results

Help Center âž” Integrations âž” Segment Integration

Segment Integration

Last updated July 30, 2024

(for helpful background on what a custom event is, what its structure is, and how they are used in Atlas, see the Custom Events article)

 Segment  is a  customer data platform  (CDP). You can consider a CDP to be a data hub where you send information in from various sources and back out to various destinations. Segment establishes a standard protocol for event types and structures so that it’s easier to add new sources and destinations, often without the need for any engineering work. They maintain a large collection of integrations to other tools, so that these connections from sources → Segment and from Segment → destinations are abstracted away from their users, leaving you the ability to focus only on the data you’re moving.

Atlas is currently integrated with Segment as a destination so that any events you currently have going into Segment can be sent to Atlas as custom events. Once the connection is established, you can manage how the events are shown in Atlas in the  App Config > Data > Custom Events  page.

Setting up Atlas as a destination

To set up Atlas as a destination in Segment:

  1. From your Segment workspace, go to Connections > Catalog and click the  Functions tab .
  2. Click Create Function.
  3. Select Destination as the function type and click Build.

After you click Build, a code editor appears. Insert the following snippet of code in the editor:

// Token is available at https://app.getatlas.io/configuration/integrations/segment
const SEGMENT_TO_ATLAS_TOKEN = '';

const BASE_URL = 'https://api.atlas.so';
const API_VERSION = 'v1';

async function onIdentify(event, settings) {
    const endpoint = `${BASE_URL}/${API_VERSION}/customers/upsert`;

    if (!event.userId) {
        throw new EventNotSupported('Mandatory parameters are missing');
    }

    if (!SEGMENT_TO_ATLAS_TOKEN) {
        console.log('Bad Configuration - SEGMENT_TO_ATLAS_TOKEN - missing');
        return;
    }
    
    let firstName;
    let lastName;

    let fullName = event.traits.name;
    
    if (fullName) {
        firstName = fullName.split(' ')[0];
        lastName = fullName.substring(firstName.length).trim()
    } else {
        firstName = event.traits.firstName || event.traits.first_name
        lastName = event.traits.lastName || event.traits.last_name
    }

    const payload = {
        userId: event.userId,
        email: event.traits.email,
        firstName: firstName,
        lastName: lastName,
    };

    if (event.traits.phone) {
        payload['phoneNumber'] = event.traits.phone
    }

    if (event.traits.company) {
        const accountData = {
            name: event.traits.company.name,
            website: event.traits.company.domain,
            externalId: event.traits.company.id,
        };
        payload['account'] = accountData;
    }

    try {
        response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${SEGMENT_TO_ATLAS_TOKEN}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });

        if (response.status >= 300) {
            throw new RetryError(`Failed with ${response.status}`);
        }
    } catch (error) {
        throw new RetryError(error.message);
    }
}

async function onTrack(event, settings) {
    const endpoint = `${BASE_URL}/${API_VERSION}/events`;
    let response;

    if (!event.userId) {
        throw new EventNotSupported('Mandatory parameters are missing');
        return;
    }

    if (!SEGMENT_TO_ATLAS_TOKEN) {
        console.log('Bad Configuration - SEGMENT_TO_ATLAS_TOKEN - missing');
        return;
    }

    const atlasEvent = {
        objectType: 'CUSTOMER',
        objectId: event.userId,
        name: 'Event Tracked',
        description: event.properties.title || '',
        payload: {
            ...event.context,
            ...event.properties
        }
    };

    try {
        response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${SEGMENT_TO_ATLAS_TOKEN}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(atlasEvent)
        });

        if (response.status >= 500 || response.status === 429) {
            throw new RetryError(`Failed with ${response.status}`);
        }
    } catch (error) {
        throw new RetryError(error.message);
    }
}

async function onPage(event, settings) {
    const endpoint = `${BASE_URL}/${API_VERSION}/events`;
    let response;

    if (!event.userId) {
        throw new EventNotSupported('Mandatory parameters are missing');
        return;
    }

    if (!SEGMENT_TO_ATLAS_TOKEN) {
        console.log('Bad Configuration - SEGMENT_TO_ATLAS_TOKEN - missing');
        return;
    }

    const atlasEvent = {
        objectType: 'CUSTOMER',
        objectId: event.userId,
        name: 'Page Viewed',
        description: event.properties.title || '',
        payload: {
            ...event.context,
            ...event.properties
        }
    };

    try {
        response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${SEGMENT_TO_ATLAS_TOKEN}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(atlasEvent)
        });

        if (response.status >= 500 || response.status === 429) {
            throw new RetryError(`Failed with ${response.status}`);
        }
    } catch (error) {
        throw new RetryError(error.message);
    }
}

async function onGroup(event, settings) {
  const endpoint = `${BASE_URL}/${API_VERSION}/accounts/upsert`;

  if (!event.userId) {
    throw new EventNotSupported("Mandatory parameters are missing");
  }

  if (!SEGMENT_TO_ATLAS_TOKEN) {
    console.log("Bad Configuration - SEGMENT_TO_ATLAS_TOKEN - missing");
    return;
  }

  const payload = {
    externalId: event.groupId,
    name: event.traits.name,
    email: event.traits.email,
  };

  try {
    response = await fetch(endpoint, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${SEGMENT_TO_ATLAS_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });
    if (response.status >= 300) {
      throw new RetryError(`Failed with ${response.status}`);
    }
  } catch (error) {
    throw new RetryError(error.message);
  }
  
}

The API Key and the APP ID are available on the Atlas dashboard at -

Once your code is saved, you can test it by grabbing a Sample Event from the events you have already brought into Segment:

Segment Integration

And you can verify the connection was successful in Atlas by going to the  App Configuration > Integrations > Segment  (note: depending on how often you have events sent to Segment, this may take some time):

Segment Integration

Was this article helpful?