Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 35 additions & 35 deletions src/connections/sources/catalog/libraries/server/node/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The [Segment Analytics Node.js Next library is open-source](https://github.com/s

All of Segment's server-side libraries are built for high-performance, so you can use them in your web server controller code. This library uses an internal queue to make Identify and Track calls non-blocking and fast. It also batches messages and flushes asynchronously to Segment's servers.

## Getting Started
## Getting started

> warning ""
> Make sure you're using a version of Node that's 18 or higher.
Expand All @@ -28,7 +28,7 @@ All of Segment's server-side libraries are built for high-performance, so you ca
pnpm add @segment/analytics-node
```

2. Initialize the `Analytics` constructor the module exposes with your Segment source **Write Key**, like so:
2. Initialize the `Analytics` constructor the module exposes with your Segment source **Write Key**:

```javascript
import { Analytics } from '@segment/analytics-node'
Expand All @@ -39,7 +39,7 @@ All of Segment's server-side libraries are built for high-performance, so you ca
const analytics = new Analytics({ writeKey: '<YOUR_WRITE_KEY>' })
```

Be sure to replace `YOUR_WRITE_KEY` with your actual **Write Key** which you can find in Segment by navigating to: **Connections > Sources** and selecting your source and going to the **Settings** tab.
Replace `YOUR_WRITE_KEY` with your actual **Write Key** which you can find in Segment by navigating to: **Connections > Sources** and selecting your source and going to the **Settings** tab.

This creates an instance of `Analytics` that you can use to send data to Segment for your project. The default initialization settings are production-ready and queue 20 messages before sending any requests.

Expand All @@ -52,7 +52,7 @@ These methods correspond with those used in the [Segment Spec](/docs/connections

### Identify

> info "Good to know"
> info ""
> For any of the different methods described on this page, you can replace the properties and traits in the code samples with variables that represent the data collected.

Identify lets you tie a user to their actions and record traits about them. It includes a unique User ID and/or anonymous ID, and any optional traits you know about them.
Expand Down Expand Up @@ -85,27 +85,27 @@ analytics.identify({
}
});
```
The call above identifies Michael by his unique User ID (the one you know him by in your database), and labels him with the `name`, `email`, `plan` and `friends` traits.
The call above identifies Michael by his unique User ID (the one you know him by in your database), and labels him with the `name`, `email`, `plan`, and `friends` traits.

An Identify call has the following fields:

Field | Details
----- | -------
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any identify call._
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: You must include at least one of `userId` or `anonymousId` in all identify calls._
`traits` _Object, optional_ | A dictionary of [traits](/docs/connections/spec/identify#traits) you know about the user. Things like: `email`, `name` or `friends`.
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any Identify call._
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: You must include at least one of `userId` or `anonymousId` in all Identify calls._
`traits` _Object, optional_ | A dictionary of [traits](/docs/connections/spec/identify#traits) you know about the user. Things like: `email`, `name`, or `friends`.
`timestamp` _Date, optional_ | A JavaScript date object representing when the identify took place. If the identify just happened, leave it out as Segment uses the server's time. If you're importing data from the past make sure to send a `timestamp`.
`context` _Object, optional_ | A dictionary of extra [context](/docs/connections/spec/common/#context) to attach to the call. _Note: `context` differs from `traits` because it is not attributes of the user itself._

Find details on the **identify method payload** in Segment's [Spec](/docs/connections/spec/identify/).
Find details on the **Identify method payload** in Segment's [Spec](/docs/connections/spec/identify/).

### Track

Track lets you record the actions your users perform. Every action triggers what Segment calls an "event", which can also have associated properties.

You'll want to track events that are indicators of success for your site, like **Signed Up**, **Item Purchased** or **Article Bookmarked**.
You'll want to track events that are indicators of success for your site, like **Signed Up**, **Item Purchased**, or **Article Bookmarked**.

To get started, Segment recommends tracking just a few important events. You can always add more later.
To get started, we recommend tracking just a few important events. You can always add more later.

Example anonymous Track call:

Expand Down Expand Up @@ -141,8 +141,8 @@ The Track call has the following fields:

Field | Details
----- | --------
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any track call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: You must include at least one of `userId` or `anonymousId` in all track calls._
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any Track call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: You must include at least one of `userId` or `anonymousId` in all Track calls._
`event` _String_ | The name of the event you're tracking. We recommend human-readable names like `Song Played` or `Status Updated`.
`properties` _Object, optional_ | A dictionary of properties for the event. If the event was `Product Added`, it might have properties like `price` or `product`.
`timestamp` _Date, optional_ | A JavaScript date object representing when the track took place. If the track just happened, leave it out and we'll use the server's time. If you're importing data from the past make sure you to send a `timestamp`.
Expand All @@ -154,7 +154,7 @@ Find details on **best practices in event naming** as well as the **Track method

The [Page](/docs/connections/spec/page/) method lets you record page views on your website, along with optional extra information about the page being viewed.

If you're using Segment's client-side set up in combination with the Node.js library, page calls are **already tracked for you** by default. However, if you want to record your own page views manually and aren't using the client-side library, read on.
If you're using Segment's client-side set up in combination with the Node.js library, Page calls are **already tracked for you** by default. However, if you want to record your own page views manually and aren't using the client-side library, read on.

Example Page call:

Expand All @@ -176,11 +176,11 @@ A Page call has the following fields:

Field | Details
----- | --------
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any page call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: at least one of `userId` or `anonymousId` must be included in any page call._
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any Page call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example, [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id)). _Note: at least one of `userId` or `anonymousId` must be included in any Page call._
`category` _String, optional_ | The category of the page. Useful for industries, like ecommerce, where many pages often live under a larger category.
`name` _String, optional_ | The name of the page, for example **Signup** or **Home**.
`properties` _Object, optional_ | A dictionary of properties of the page. A few properties specially recognized and automatically translated: `url`, `title`, `referrer` and `path`, but you can add your own too.
`properties` _Object, optional_ | A dictionary of properties of the page. A few properties specially recognized and automatically translated: `url`, `title`, `referrer`, and `path`, but you can add your own too.
`timestamp` _Date, optional_ | A JavaScript date object representing when the Page took place. If the Page just happened, leave it out and Segment will use the server's time. If you're importing data from the past make sure you to send a `timestamp`.
`context` _Object, optional_ | A dictionary of extra [context](docs/connections/spec/common/#context) to attach to the call. _Note: `context` differs from `traits` because it is not attributes of the user itself._

Expand All @@ -190,7 +190,7 @@ Find details on the **Page payload** in the [Segment Spec](/docs/connections/spe

Group lets you associate an [identified user](/docs/connections/sources/catalog/libraries/server/node/#identify) with a group. A group could be a company, organization, account, project or team. It also lets you record custom traits about the group, like industry or number of employees.

This is useful for tools like [Intercom](/docs/connections/destinations/catalog/intercom/), [Preact](/docs/connections/destinations/catalog/preact/) and [Totango](/docs/connections/destinations/catalog/totango/), as it ties the user to a **group** of other users.
This is useful for tools like [Intercom](/docs/connections/destinations/catalog/intercom/), [Preact](/docs/connections/destinations/catalog/preact/), and [Totango](/docs/connections/destinations/catalog/totango/), as it ties the user to a **group** of other users.

Example Group call:

Expand All @@ -209,21 +209,21 @@ The Group call has the following fields:

Field | Details
----- | --------
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any group call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are (for example), [the anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id). _Note: at least one of `userId` or `anonymousId` must be included in any group call._
`userId` _String, optional_ | The ID for this user in your database. _Note: at least one of `userId` or `anonymousId` must be included in any Group call.
`anonymousId` _String, optional_ | An ID associated with the user when you don't know who they are. For example, the [anonymousId generated by `analytics.js`](/docs/connections/sources/catalog/libraries/website/javascript/#anonymous-id). _Note: at least one of `userId` or `anonymousId` must be included in any Group call._
`groupId` _string | The ID of the group.
`traits` _dict, optional_ | A dict of traits you know about the group. For a company, they might be things like `name`, `address`, or `phone`. [Learn more about traits](/docs/connections/spec/group/#traits).
`context` _dict, optional_ | A dict containing any context about the request. To see the full reference of supported keys, check them out in the [context reference](/docs/connections/spec/common/#context)
`timestamp` _datetime, optional_ | A `datetime` object representing when the Group took place. If the Group just happened, leave it out and Segment will use the server's time. If you're importing data from the past make sure you send `timestamp`.
`context` _dict, optional_ | A dict containing any context about the request. To see the full reference of supported keys, check them out in the [context reference](/docs/connections/spec/common/#context).
`timestamp` _datetime, optional_ | A `datetime` object representing when the Group call took place. If the Group call just happened, leave it out and Segment will use the server's time. If you're importing data from the past make sure you send `timestamp`.
`integrations` _dict, optional_ | A dictionary of destinations to enable or disable.

Find more details about Group, including the **Group payload**, in the [Segment Spec](/docs/connections/spec/group/).

### Alias

The Alias call allows you to associate one identity with another. This is an advanced method and should not be widely used, but is required to manage user identities in _some_ destinations. Other destinations do not support the alias call.
The Alias call allows you to associate one identity with another. This is an advanced method and should not be widely used, but is required to manage user identities in _some_ destinations. Other destinations do not support the Alias call.

In [Mixpanel](/docs/connections/destinations/catalog/mixpanel/#alias) it's used to associate an anonymous user with an identified user once they sign up. For [Kissmetrics](/docs/connections/destinations/catalog/kissmetrics/#alias), if your user switches IDs, you can use 'alias' to rename the 'userId'.
In [Mixpanel](/docs/connections/destinations/catalog/mixpanel/#alias) it's used to associate an anonymous user with an identified user once they sign up. For [Kissmetrics](/docs/connections/destinations/catalog/kissmetrics/#alias), if your user switches IDs, you can use the Alias call to rename the `userId`.

Example Alias call:

Expand Down Expand Up @@ -464,11 +464,11 @@ analytics.on('http_request', (event) => console.log(event))
}
```

### Emitter Types
### Emitter types

The following table documents all the emitter types available in the Analytics Node.js library:

| Emitter Type | Description |
| Emitter type | Description |
|-------------------|-----------------------------------------------------------------------------|
| `error` | Emitted when there is an error after SDK initialization. |
| `identify` | Emitted when an Identify call is made.
Expand Down Expand Up @@ -534,7 +534,7 @@ Deregister a plugin by using:
await analytics.deregister("pluginNameA", "pluginNameB") // takes strings
```

## Selecting Destinations
## Selecting destinations

The Alias, Group, Identify, Page, and Track calls can all be passed an object of `integrations` that lets you turn certain destinations on or off. By default all destinations are enabled.

Expand All @@ -556,19 +556,19 @@ In this case, Segment specifies that they want this Track event to only go to Ve

Destination flags are **case sensitive** and match [the destination's name in the docs](/docs/connections/destinations/) (for example, "AdLearn Open Platform", "awe.sm", or "MailChimp"). In some cases, there may be several names for a destination; if that happens you'll see a "Adding (destination name) to the Integrations Object" section in the destination's doc page with a list of valid names.

**Note:**
Keep in mind:

- Business Tier users can filter Track calls right from the Segment UI on your source schema page. Segment recommends using the UI if possible since it's a much simpler way of managing your filters and can be updated with no code changes on your side.
- Business Tier users can filter Track calls right from the Segment UI on your source schema page. We recommend using the UI if possible since it's a much simpler way of managing your filters and can be updated with no code changes on your side.

- If you are on a grandfathered plan, events sent server-side that are filtered through the Segment dashboard still count towards your API usage.

## Historical Import
## Historical import

You can import historical data by adding the `timestamp` argument to any of your method calls. This can be helpful if you've just switched to Segment.

Historical imports can only be done into destinations that can accept historical timestamped data. Most analytics tools like Mixpanel, Amplitude, Kissmetrics, etc. can handle that type of data just fine. One common destination that does not accept historical data is Google Analytics since their API cannot accept historical data.
Historical imports can only be done into destinations that can accept historical timestamped data. Most analytics tools like Mixpanel, Amplitude, and Kissmetrics can handle that type of data just fine. One common destination that does not accept historical data is Google Analytics since their API cannot accept historical data.

**Note:** If you're tracking things that are happening right now, leave out the `timestamp` and Segment's servers will timestamp the requests for you.
**Note**: If you're tracking things that are happening right now, leave out the `timestamp` and Segment's servers will timestamp the requests for you.


## Batching
Expand All @@ -582,7 +582,7 @@ By default, Segment's library will flush:
- Every 15 messages (controlled by `settings.flushAt`).
- If 10 seconds has passed since the last flush (controlled by `settings.flushInterval`)

There is a maximum of `500KB` per batch request and `32KB` per call.
There is a maximum of `500 KB` per batch request and `32 KB` per call.

If you don't want to batch messages, you can turn batching off by setting the `flushAt` setting to `1`, like so:

Expand All @@ -606,7 +606,7 @@ analytics.track({
)
```

## Multiple Clients
## Multiple clients

Different parts of your application may require different types of batching, or even sending to multiple Segment sources. In that case, you can initialize multiple instances of `Analytics` with different settings:

Expand All @@ -618,7 +618,7 @@ const appAnalytics = new Analytics({ writeKey: 'APP_WRITE_KEY' });

Segment attempts to use the global `fetch` implementation if available in order to support several diverse environments. Some special cases (for example, http proxy) may require a different implementation for http communication. You can provide a customized wrapper in the Analytics configuration to support this. Here are a few approaches:

Use a custom fetch-like implementation with proxy (simple, recommended)
Use a custom fetch-like implementation with proxy (Recommended)
```javascript
import { HTTPFetchFn } from '../lib/http-client'
import axios from 'axios'
Expand Down
Loading