Segment is a customer data platform that helps businesses collect, manage, and analyze customer data from multiple sources. It streamlines data integration, ensures data quality, and aids in compliance with regulations. Segment’s tools enable better understanding of customer behavior and facilitate personalized customer experiences. It’s useful for marketing, analytics, and product teams in diverse industries.

If this is your first time working with the tool, consider consulting the ‘Get Started’ guide in Segment’s official documentation.

Examples Use Case

Enhancing Customer Engagement and Conversion Rates

1

Data Integration with Segment

  • The e-commerce platform uses Segment to collect and unify customer data from various sources like website visits, purchase history, and customer interactions.
  • Segment helps in creating a unified customer profile by consolidating data from different touchpoints – mobile app usage, website browsing patterns, and previous purchase behavior.
2

Behavioral Analysis and Segmentation

  • The data collected is analyzed to understand customer preferences, buying patterns, and engagement levels.
  • Customers are segmented into different groups based on their behavior, interests, and purchase history. For instance, one segment might include frequent shoppers, while another might focus on those who browse but rarely purchase.
3

Personalized Notification with Novu

  • Novu is used to craft and send personalized notifications to these segmented groups.
  • For frequent shoppers, notifications about new arrivals or exclusive deals might be sent. For those who browse but rarely buy, notifications could include special discount codes or reminders about items left in the cart.

Example of a special offer email in Novu's email editor

4

Trigger-Based Notifications

  • Notifications can also be triggered based on specific customer actions. For example, if a customer views a product but doesn’t make a purchase, they might receive a notification later highlighting a special offer on that product.

Example of an 'Abandoned Cart Recovery' workflow in Novu

5

Feedback Loop for Continuous Improvement

  • Customer responses to these notifications are fed back into Segment. This data is used to refine customer profiles and segmentation strategies continuously.
  • The effectiveness of different types of notifications is analyzed to optimize future communication.

Outcome:

  • Enhanced customer engagement through personalized and timely notifications.

  • Improved conversion rates by targeting customers with relevant offers based on their behavior and preferences.

  • Greater customer loyalty due to a tailored shopping experience.

Setting Novu as a Destination

As of Segment doesn’t have a native Novu Destination integration yet .

We will be using Destination Functions. Destination functions allow you to transform and annotate your Segment events and send them to any external tool or API without worrying about setting up or maintaining any infrastructure.

Create a destination function

  • From your workspace, go to Connections > Catalog and click the Functions tab.
  • Click New Function.
  • Select Destination as the function type and click Build.
  • After you click Build, a code editor appears. Use the editor to write the code for your function, configure settings, and test the function’s behavior.
Want to see some example functions? Check out the templates available in the Functions UI, or in the open-source Segment Functions Library.

Code the destination function

Segment invokes a separate part of the function (called a “handler”) for each event type that you send to your destination function.

Your function isn’t invoked for an event if you’ve configured a destination filter, and the event doesn’t pass the filter.

The default source code template includes handlers for all event types. You don’t need to implement all of them - just use the ones you need, and skip the ones you don’t.

Destination functions can define handlers for each message type in the Segment spec:

  • onIdentify
  • onTrack
  • onPage
  • onScreen
  • onGroup
  • onAlias
  • onDelete
  • onBatch

Each of the functions above accepts two arguments:

event - Segment event object, where fields and values depend on the event type. For example, in “Identify” events, Segment formats the object to match the Identify spec.

settings - Set of settings for this function. The example below shows a destination function that listens for “Track” events, and sends some details about them to an external service.

async function onTrack(event) {
  await fetch('https://example-service.com/api', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      event_name: event.event,
      event_properties: event.properties,
      timestamp: event.timestamp
    })
  })
}

To change which event type the handler listens to, you can rename it to the name of the message type.

For example, if you rename this function onIdentify, it listens for “Identify” events instead.

If you you need an example of Novu destination function, you can find it in here. Feel free to submit your function examples as well!

Sending a payload to Novu

Now let’s learn how to send a payload to Novu based on the onTrack event function:

To successfully send a payload to Novu, triggering the appropriate workflow and delivering it to the correct customer, please ensure that you provide the following information:

  1. Novu’s Workflow Identifier.
  2. Subscriber ID (Please ensure that the Subscriber ID is both unique and consistent across all of your databases).
  3. Your Novu API Key.
  4. Novu’s Event Trigger API Endpoint
async function onTrack(event, settings) {
	const eventProperties = event.properties;

	if (!eventProperties.environment) {
		throw new InvalidEventPayload('environment property is required');
	}
	if (!eventProperties.name) {
		throw new InvalidEventPayload('Workflow name property is required');
	}

	console.log('environment:', eventProperties.environment);

	const payload = {
		name: eventProperties.name,
		to: {
			subscriberId: eventProperties.user.subscriberId,
			email: eventProperties.user.email,
			firstName: eventProperties.user.firstName,
			lastName: eventProperties.user.lastName
		},
		payload: { eventProperties }
	};
	const endpoint = settings.novuEndpoint;
	console.log('endpoint:', endpoint);

	const ApiKey = settings.novuApiKey; // Your NOVU API key
	if (eventProperties.environment === settings.environment) {
		let response;
		try {
			response = await fetch(endpoint, {
				method: 'POST',
				headers: {
					Authorization: `ApiKey ${ApiKey}`,
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(payload)
			});
		} catch (error) {
			// Retry on connection error
			throw new RetryError(error.message);
		}
		if (response.status >= 500 || response.status === 429) {
			// Retry on 5xx (server errors) and 429s (rate limits)
			throw new RetryError(`Failed with ${response.status}`);
		}
	}
}

Create Settings and Secrets

Segment’s settings allow you to pass configurable variables to your function, which is the best way to pass sensitive information such as security tokens. For example, you might use settings as placeholders to use information such as an API endpoint and API key. You can learn more about it here.

Click Add Setting to add your new setting.

Now, while configuring the function, Add these three variables to be then used in the code exposed in the settings function param.

The variables you need to run the provided snippit

Test the destination function

You can test your code directly from the editor in two ways:

1. Use sample events for testing Click Use Sample Event and select the source to use events from.

Example from Segment's documention event sources

Click Run to test your function with the event you selected.

2. Test using manual input You can also manually include your own JSON payload of a Segment event, instead of fetching a sample from one of your workspace sources.

Here is the the event example JSON we will use

{
  "type": "track",
  "event": "User Abandoned Cart",
  "properties": {
    "name": "abandoned-cart-recovery-workflow",
    "user": {
      "subscriberId": "63da8ee0c037e013fd790ffd",
      "email": "hi@hi.com",
      "firstName": "John",
      "lastName": "Doe"
    },
    "environment": "development"
  }
}

We will now execute the function based on the manual event input we’ve provided. This function sends a trigger to Novu, prompting to take action and send the user an email to return and the purchase.

Whether you chose the first or second option to test your Destination Function, you can also check if the function triggered your workflow and whether it was delivered through Novu’s Activity Feed.

This guide was inspired by the following resources: