# Segment

## Overview <a href="#braze-integration-0" id="braze-integration-0"></a>

[Segment](https://segment.com/) is a platform that captures and stores all first-party customer data regarding your product or service in a centralized place. More specifically, Segment collects events from your interfaces (websites, web apps, etc.), and from that information, helps you create more personalized customer experiences across various channels.

We will plug Lob into our Segment flow by making a custom destination function. Destinations are business tools or apps to which you can send the data you collect in Segment. Depending on which mailpiece form factor you want to send (postcard, letter, etc.), building a destination function that sends it merely involves reading the data and calling Lob’s API. These steps are outlined below.

## Getting Started <a href="#step-1-add-custom-attributes-1" id="step-1-add-custom-attributes-1"></a>

* Make sure you have a [Lob account](https://dashboard.lob.com/login) and your [API keys](/account-management/api-keys.md). **It is highly recommended that you use your (secret) test API key first**
* Have a [creative file](/print-and-mail/designing-mail-creatives/creative-formatting.md) ready to use (hosted PDF file or HTML template)
* Have your [Segment account](https://app.segment.com/login) ready

## Connect Segment to Lob using Destination Functions:

{% hint style="success" %}
Learn more about destination functions API at <https://segment.com/docs/connections/destinations/destination-functions>
{% endhint %}

1. In the sidebar, navigate to “Connections” -> “Catalog,” and then click the Functions tab:

<figure><img src="https://lh6.googleusercontent.com/u4dkWGi3cXPVy2EwYfnorsws2CE1vlr6Hjr-QqPSVl0uvq_3Jt8pEhDda1l8beICIYGAY7IfS8Rnh21_ARoZ1PBhhNDKMHJpHPi1sDJmbXcpJx7uNQm7M9ymvdVTENIw4rEY9_p9M1XsyY_N9tQRSkA" alt=""><figcaption></figcaption></figure>

2. Click the “New Function” button:

<figure><img src="https://lh6.googleusercontent.com/h-tn8kpaUQeXWFa-U8RmN9q7MWVhAXLz-DYk9vsg-KBKKMXJGJWifGS1CqFFCmZnF7Crnf6uCI4IHtg1BrRSHibtxkRBu-2QLcDUzw8wwubpmGikj258CUfnYEmLXFEssZdDDuY5OFmGPDtKNXFLASk" alt=""><figcaption></figcaption></figure>

3. Under “Select Function Type,” click “Destination,” and then click “Build”:

<figure><img src="https://lh5.googleusercontent.com/5B3fTcqlZDxMS-EuewutqRxt1-sv2MF9xQB1gOsvQAUWgCtZuQBtpRJtD8Ho627NXGwtygSB9CwTQ0O_jIes_blIMlCw9zEn2k1KGpG6bdgzYLm2aRv8lIi3Yt5lFTkjNm-rXLQLJ9AdIGxq71HmzrI" alt=""><figcaption></figcaption></figure>

4. Enter your Javascript code in the editor on the left, and test your function on the right; refer to [the following section ](#segment-events-by-mail-form-factor)on form factors for details. Click “Configure” when done:

<figure><img src="https://lh4.googleusercontent.com/AomPmN1QA1Te1ti8TV03TQZHrrEpLuww5lZztdlHkzaEw-l7G6oyrzhihBohkUQpkc55rrRai6YfKKGv_hgYF3xKZaaKPNdU7kGCqDKFR5W0eOSXSEdK45X4Ua3W20UP5fUc4bx7Pz6haoedy-R41oQ" alt=""><figcaption></figcaption></figure>

5. Give the function a name (required), description, and logo, and click “Create Function” to save:&#x20;

<figure><img src="https://lh6.googleusercontent.com/UnC-9YqHd-LyGJBlcuCTplKNk6nGOKtgu0uvAEGr_weOeBFRwM50Yzj1xOpeL4-73w8ZbeEel9O7HB1tnqVElWbr4gYVRM98EbyfXXO-57TE_H2uI8V6iPqma3gm-JgYms3ywTjFS7q0hGNoFlPbEiI" alt=""><figcaption></figcaption></figure>

## Segment Events by Mail Form Factor

The following are sample functions to send a Lob mailpiece from a given Segment event, organized by mailpiece. Segment provides six different event types that destination functions can operate on:

* [Identify](https://segment.com/docs/connections/spec/identify/): who is the customer?
* [Track](https://segment.com/docs/connections/spec/track/): what are they doing?
* [Page](https://segment.com/docs/connections/spec/page/): what web page are they on?
* [Screen](https://segment.com/docs/connections/spec/screen/): what app screen are they on?
* [Group](https://segment.com/docs/connections/spec/group/): what account or organization are they part of?
* [Alias](https://segment.com/docs/connections/spec/alias/): what was their past identity?

**The following sample code translates Track events into Lob mailpieces by defining an onTrack function. (For other functionalities, just define a similarly named function, e.g., onPage for Page events.)**

<details>

<summary>Postcards</summary>

```javascript
/**
* @param {SpecTrack} event The track event
* @param {Object.<string, any>} settings Custom settings
* @return any
*/
async function onTrack(event, settings) {
 const body = {
   description: 'Description of the card,'
   to: {
     name: event.properties.name,
     address_line1: event.properties.address.line1,
     address_line2: event.properties.address.line2,
     address_city: event.properties.address.city,
     address_state: event.properties.address.state,
     address_zip: event.properties.address.zip
   },
   front:
     "<html style='padding: 1in; font-size: 50;'>Front side for {{name}}</html>",
   back: "<html style='padding: 1in; font-size: 20;'>Back side for {{name}}</html>",
   merge_variables: {
     name: event.properties.name
   }
 };


 const response = await fetch('https://api.lob.com/v1/postcards', {
   method: 'POST',
   headers: {
     Authorization: `Basic ${btoa(settings.apiKey + ':')}`,
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(body)
 });


 return response.json();
}
```

</details>

<details>

<summary>Letters</summary>

```javascript
/**
* Handle track event
* @param  {SegmentTrackEvent} event
* @param  {FunctionSettings} settings
*/
async function onTrack(event, settings) {
 const body = {
   description: 'Description of the letter',
   to: {
     name: event.properties.name,
     address_line1: event.properties.address.line1,
     address_line2: event.properties.address.line2,
     address_city: event.properties.address.city,
     address_state: event.properties.address.state,
     address_zip: event.properties.address.zip
   },
   from: {
     name: event.properties.return_addr.name,
     address_line1: event.properties.return_addr.line1,
     address_line2: event.properties.return_addr.line2,
     address_city: event.properties.return_addr.city,
     address_state: event.properties.return_addr.state,
     address_zip: event.properties.return_addr.zip
   },
   file: "<html style='padding: 1in; font-size: 50;'>Front side for {{name}}</html>",
   color: 'false',
   use_type: 'marketing',
   merge_variables: {
     name: event.properties.name
   }
 };


 const response = await fetch('https://api.lob.com/v1/letters', {
   method: 'POST',
   headers: {
     Authorization: `Basic ${btoa(settings.apiKey + ':')}`,
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(body)
 });


 return response.json();
}

```

</details>

<details>

<summary>Self Mailers</summary>

```javascript
/**
* Handle track event
* @param  {SegmentTrackEvent} event
* @param  {FunctionSettings} settings
*/
async function onTrack(event, settings) {
 const body = {
   description: 'Description of the self-mailer',
   to: {
     name: event.properties.name,
     address_line1: event.properties.address.line1,
     address_line2: event.properties.address.line2,
     address_city: event.properties.address.city,
     address_state: event.properties.address.state,
     address_zip: event.properties.address.zip
   },
   inside:
     "<html style='padding: 1in; font-size: 50;'>Inside side for {{name}}</html>",
   outside:
     "<html style='padding: 1in; font-size: 20;'>Outside side for {{name}}</html>",
   use_type: 'marketing',
   merge_variables: {
     name: event.properties.name
   }
 };


 const response = await fetch('https://api.lob.com/v1/self_mailers', {
   method: 'POST',
   headers: {
     Authorization: `Basic ${btoa(settings.apiKey + ':')}`,
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(body)
 });


 return response.json();
}

```

</details>

<details>

<summary>Checks</summary>

```javascript
/**
* Handle track event
* @param  {SegmentTrackEvent} event
* @param  {FunctionSettings} settings
*/
async function onTrack(event, settings) {
 const body = {
   description: 'Description of the check',
   to: {
     name: event.properties.name,
     address_line1: event.properties.address.line1,
     address_line2: event.properties.address.line2,
     address_city: event.properties.address.city,
     address_state: event.properties.address.state,
     address_zip: event.properties.address.zip
   },
   from: {
     name: event.properties.return_addr.name,
     address_line1: event.properties.return_addr.line1,
     address_line2: event.properties.return_addr.line2,
     address_city: event.properties.return_addr.city,
     address_state: event.properties.return_addr.state,
     address_zip: event.properties.return_addr.zip
   },
   bank_account: 'bank_a4fc08e61e12c6c',
   message: 'INSERT MESSAGE HERE',
   amount: 0, //Insert an amount here
   use_type: 'marketing',
   merge_variables: {
     name: event.properties.name
   }
 };


 const response = await fetch('https://api.lob.com/v1/checks', {
   method: 'POST',
   headers: {
     Authorization: `Basic ${btoa(settings.apiKey + ':')}`,
     'Content-Type': 'application/json'
   },
   body: JSON.stringify(body)
 });


 return response.json();
}

```

</details>

{% hint style="success" %}
**Remember to test your mail sent through Segment by using your test API key first.** Once you do, plug in your live key, and enjoy sending intelligent, automated mail pieces with Lob and Segment!
{% endhint %}

## Conclusion

Given how useful Segment is for integrating multiple different interfaces for collecting and operating on customer data, this tutorial gives us the ability to add Lob as one of many possible powerful tools for accomplishing data-driven, instantaneous operations on that data. Luckily, plugging Lob into Segment is as easy as making a destination function and using it in your workflows.

## Resources

Here are two other resources that might help with crafting your workflow:

* [Segment's docs on connections, the meat and potatoes of making workflows](https://segment.com/docs/connections/)<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.lob.com/print-and-mail/integrations/api-integrations/segment.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
