> For the complete documentation index, see [llms.txt](https://docs.chord.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/useanalytics.md).

# useAnalytics

{% hint style="info" %}
**This page's documentation only applies to Chord's** [**Next.js starter**](https://github.com/chordcommerce/nextjs-starter-autonomy) **prior to the release of the** [React](/chord-oms/developer-tools/react.md)**. The Next.js starter now uses the React SDK and does not use the methods documented on this page. Check out the** [**React SDK Reference**](https://docs-beta.chord.co/chord-ui/module-react-autonomy) **for complete documentation, and the** [React SDK Migration Guide](/chord-oms/developer-tools/next-js/guides/react-sdk-migration-guide.md)**for details on how to upgrade.**
{% endhint %}

The `useAnalytics` hook returns a set of functions that send a tracking event to Segment.

The starter sends most Segment events about user actions automatically, when other hooks like `useCart` are used. However, some events need to be closely tied to the UI, like click tracking, and must be sent explicitly by React components. These events are available via the `useAnalytics` hook.

## Example

{% code title="useAnalytics" %}

```javascript
import { useAnalytics } from '~/hooks/actions'
import Link from '~/components/Generic/Link'

const ProductLink = ({ children, slug }) => {
  const { trackClickProduct } = useAnalytics()
  const url = `/products/${slug}/`

  return (
    <Link href={url} onClick={() => trackClickProduct(slug)}>
      {children}
    </Link>
  )
}
```

{% endcode %}

## Returns

The `useAnalytics` hook returns an object with these properties:

| Property                  | Description                                                       |
| ------------------------- | ----------------------------------------------------------------- |
| `trackClickCollection`    | A function that sends a `Collection Clicked` event to Segment.    |
| `trackClickProduct`       | A function that sends a `Product Clicked` event to Segment.       |
| `trackCreateStockRequest` | A function that sends a `Stock Request Created` event to Segment. |
| `trackViewCart`           | A function that sends a `Cart Viewed` event to Segment.           |

## Functions

### trackClickCollection

The `trackClickCollection` function fires a `Collection Clicked` event to Segment. You should call this function when the user clicks on a link to a collection.

**Arguments:**

`trackClickCollection(title, slug, url)`

| Argument | Type   | Description                                          |
| -------- | ------ | ---------------------------------------------------- |
| `title`  | String | The title of the collection.                         |
| `slug`   | String | The slug of the collection.                          |
| `url`    | String | The URL of the collection landing page on your site. |

**Returns:**

`undefined`

**Example:**

{% code title="trackClickCollection" %}

```javascript
import { useAnalytics } from '~/hooks/actions'
import Link from '~/components/Generic/Link'

const CollectionLink = ({ title, slug, children }) => {
  const { trackClickCollection } = useAnalytics()
  const url = `/shop/?collection=${slug}`

  return (
    <Link href={url} onClick={() => trackClickCollection(title, slug, url)}>
      {children}
    </Link>
  )
}
```

{% endcode %}

### trackClickProduct

The `trackClickProduct` function sends a `Product Clicked` event to Segment. You should call this function when the user clicks on a link to a product.

**Arguments:**

`trackClickProduct(slug)`

| Argument | Type   | Description              |
| -------- | ------ | ------------------------ |
| `slug`   | String | The slug of the product. |

**Returns:**

`undefined`

**Example:**

{% code title="trackClickProduct" %}

```javascript
import { useAnalytics } from '~/hooks/actions'
import Link from '~/components/Generic/Link'

const ProductLink = ({ children, slug }) => {
  const { trackClickProduct } = useAnalytics()
  const url = `/products/${slug}/`

  return (
    <Link href={url} onClick={() => trackClickProduct(slug)}>
      {children}
    </Link>
  )
}
```

{% endcode %}

### trackCreateStockRequest

The `trackCreateStockRequest` function sends a `Stock Request Created` event to Segment.

{% hint style="warning" %}
This function does not add the customer email address to a waitlist in the OMS. It only sends the event to Segment. The `useProduct().createStockRequest()` function adds the customer to a waitlist in the OMS and also sends a `Stock Request Created` event to Segment, so you should only use this function if you want to manage the product waitlist outside the OMS.
{% endhint %}

**Arguments:**

| Argument | Type   | Description                                                              |
| -------- | ------ | ------------------------------------------------------------------------ |
| `email`  | String | The email address to sent an email to when the variant is back in stock. |
| `sku`    | String | The variant SKU.                                                         |

**Returns:**

`undefined`

**Example:**

{% code title="trackCreateStockRequest" %}

```javascript
import { useAnalytics } from '~/hooks/actions'

const StockRequestForm = ({ sku }) => {
  const { trackCreateStockRequest } = useAnalytics()
  const onSubmit = ({ email, sku }) => {
    trackCreateStockRequest(email, sku)
  }

  // return sign up form
}
```

{% endcode %}

### trackEmailCaptured

The `trackEmailCaptured` function sends a `Email Captured` event to Segment. You should call this whenever the user enters an email. Examples of this can include newsletter signups, coupon pop-ups and/or logins. This function will also [identify the user to Segment](https://segment.com/docs/connections/spec/identify/) so that all subsequent tracking calls will be associated with this email.

**Arguments:**

`trackEmailCaptured({ email, name, webPlacement })`

| Argument       | Type                |                                                                                                                                                                                                                                                                                    |
| -------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `email`        | String              | The email address that was captured.                                                                                                                                                                                                                                               |
| `name`         | String \| undefined | The name of the user, if it is known.                                                                                                                                                                                                                                              |
| `webPlacement` | Object \| undefined | Data about where on the site the email was captured. The following properties on this are all optional:\* component - HTML component within the UX, such as header, footer, modal\* page - Page of the website (or Sitewide for whole website)\* website - Hostname of the website |

**Returns**:

`undefined`

**Example:**

{% code title="trackEmailCaptured" %}

```javascript
import { useAnalytics } from '~/hook/actions'

const NewsletterForm = () => {
  const { trackEmailCaptured } = useAnalytics()
  const handleSubmit = useCallback((event) => {
    event.preventDefault()

    const payload = {
      email: event.currentTarget.elements['email'].value,
      name: event.currentTarget.elements['name']?.value,
      webPlacement: {
        component: 'footer',
        page: 'Sitewide',
        website: window.location.host,
      },
    }

    trackEmailCaptured(payload)
  }, [trackEmailCaptured])

  return (
    <form onSubmit={handleSubmit}>
      <p>Sign up for our newsletter!</p>
      <input type="email" name="email" placeholder="Your Email" required />
      <button type="submit">Sign Up</button>
    </form>
  )
}
```

{% endcode %}

### trackViewCart

The `trackViewCart` function sends a `Cart Viewed` event to Segment. You should call this function when the cart page is viewed.

**Arguments:**

`trackViewCart()`

None.

**Returns:**

`undefined`

**Example:**

{% code title="trackViewCart" %}

```javascript
import { useAnalytics } from '~/hooks/actions'

const CartPage = () => {
  const { trackViewCart } = useAnalytics()
  useEffect(trackViewCart, [])

  // return cart page
}
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/useanalytics.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
