Skip to content

Analytics.js cleanup (part 1) #7653

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 5, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ redirect_from: '/connections/sources/catalog/libraries/website/javascript/persis
strat: ajs
---

This page explains what data Analytics.js stores on the client and how to override and change what and how this data is stored.
This page explains what data Analytics.js stores on the client and shows you how to modify or override that storage behavior.

## Segment ID persistence

<!-- Note: 1st 2 paragraphs copied from identity.md -->

To ensure high fidelity, first-party customer data, Segment writes the user's IDs to the user's local storage and uses that as the Segment ID on the cookie whenever possible. Local storage is for storing this type of first-party customer information.
To ensure high-fidelity, first-party customer data, Segment writes the user's IDs to the user's local storage and uses them as the Segment ID in the cookie whenever possible. Local storage is intended for storing first-party customer information.

If a user returns to your site after the cookie expires, Analytics.js looks for an old ID in the user's `localStorage`, and if one is found, it sets as the user's ID again in the new cookie. If a user clears their cookies _and_ `localStorage`, all of the IDs are removed, and the user gets a completely new [`anonymousID`](/docs/connections/sources/catalog/libraries/website/javascript/identity/#anonymous-ids) when they next visit the page.
If a user returns to your site after the cookie expires, Analytics.js looks for an old ID in the user's `localStorage`, and if one is found, it sets it as the user's ID again in the new cookie. If a user clears their cookies _and_ `localStorage`, all of the IDs are removed, and the user gets a completely new [`anonymousID`](/docs/connections/sources/catalog/libraries/website/javascript/identity/#anonymous-ids) when they next visit the page.

### Cookie settings

Expand All @@ -26,7 +26,7 @@ Here is the full list of available parameters with their default values:
| Parameter | Description | Default value |
| --- | --- | --- |
| `domain` | The domain to set the cookie to. This must match the domain of the JavaScript origin. If an Analytics.js cookie already exists at the top-level domain, Segment carries the same cookie value to any subdomains, despite `domain` configuration. | Top-level domain |
| `maxage` | The maximum amount of time in days before the cookie expires. Browsers may clear cookies before this elapses. | 1 year |
| `maxage` | The maximum amount of time in days before the cookie expires. Browsers may clear cookies before this time elapses. | 1 year |
| `path` | The path the cookie is valid for. | `"/"` |
| `sameSite` | This prevents the browser from sending the cookie along with cross-site requests. | `Lax` |
| `secure` | This determines whether cookies can only be transmitted over secure protocols such as https. | `false` |
Expand Down Expand Up @@ -60,7 +60,7 @@ To set cookie values using the [NPM package](https://github.com/segmentio/analyt
})
```
> info ""
> Chrome has a maximum limit of 400 days for cookies. If a value is set beyond that, then Chrome sets the upper limit to 400 days instead of rejecting it. Visit Chrome's [docs](https://developer.chrome.com/blog/cookie-max-age-expires/){:target="blank"} to learn more.
> Chrome has a maximum limit of 400 days for cookies. If a value is set beyond that, then Chrome sets the upper limit to 400 days instead of rejecting it. Visit [Chrome's docs](https://developer.chrome.com/blog/cookie-max-age-expires/){:target="blank"} to learn more.

### Device-mode destination cookies

Expand Down Expand Up @@ -144,13 +144,13 @@ You can still manually track identity by calling `analytics.identify()` with the

### Event retries

Analytics.js tries to detect when a page is about to be closed and saves pending events to `localStorage`. When the user navigates to another page within the same domain, Analytics.js attempts to send any events it finds in localStorage.
Analytics.js tries to detect when a page is about to be closed and saves pending events to `localStorage`. When the user navigates to another page within the same domain, Analytics.js attempts to send any events it finds in `localStorage`.

When `disableClientPersistence` is set to `true`, Analytics.js won't store any pending events into `localStorage`.

## Client-side cookie methods (get, set, clear)

To access or assign a value to a cookie outside of the standard Segment methods (track/identify/page/group), you can use the following methods. To access the cookie's value, pass an empty `()` at the end of the method. To assign the value, include the string value inside those parenthesis, for example, `('123-abc')`. To clear or remove the value for a specific field, pass in an empty value of its type. For example, for string `('')`, or for object `({})`.
To access or assign a value to a cookie outside of the standard Segment methods (Track, Identify, Page, and Group), you can use the following methods. To access the cookie's value, pass an empty `()` at the end of the method. To assign the value, include the string value inside those parenthesis, for example, `('123-abc')`. To clear or remove the value for a specific field, pass in an empty value of its type. For example, for string `('')`, or for object `({})`.

<table class="horizontal-scroll">
<tr style="background-color: #fafbff; font-size: 10px;">
Expand Down Expand Up @@ -203,17 +203,17 @@ To access or assign a value to a cookie outside of the standard Segment methods
</tr>
</table>

To retrieve a specific user trait using the Analytics.js Get method, you can access the trait by invoking `analytics.user().traits().firstName`. This returns the firstName trait of the user.
To retrieve a specific user trait using the Analytics.js Get method, you can access the trait by invoking `analytics.user().traits().firstName`. This returns the `firstName` trait of the user.

To retrieve a specific group trait, you can use the method `analytics.group().traits().companyName`. This returns the companyName trait of the group.
To retrieve a specific group trait, you can use the method `analytics.group().traits().companyName`. This returns the `companyName` trait of the group.

When you access specific traits stored in the browser's localStorage, you need to utilize the [JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse){:target="_blank"} method because the stored data is typically in string format.
When you access specific traits stored in the browser's `localStorage`, you need to use the [JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse){:target="_blank"} method because the stored data is typically in string format.

## Storage Priority
## Storage priority

By default, Analytics.js uses `localStorage` as its preferred storage location, with Cookies as a fallback when `localStorage` is not available or not populated. An in-memory storage is used as a last fallback if all the previous ones are disabled.

Default Storage Priority:
Default storage priority:

```md
LocalStorage -> Cookie -> InMemory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,41 +13,41 @@ You cannot use custom proxy setup for Analytics.js CDN or Tracking API with devi

{% include content/domain-delegation-solutions.md %}

## Custom Proxy prerequisites
## Custom proxy prerequisites

To set up a custom proxy, you need:

- Access to your site DNS settings
- Access to your site's DNS settings
- A CDN you can serve assets from
- Access to the CDN settings
- A security certificate for the proxy domain

> info "Custom Proxy Troubleshooting"
> info "Custom proxy troubleshooting"
> If you experience issues configuring a custom proxy, contact your organization's IT department for help. Segment does not have access to the resources you need to configure a custom proxy.

This guide explains how to set up a custom proxy in CloudFront. You can apply these principles to almost any modern CDN that supports proxies.

You need to set up two important parts, regardless of the CDN provider you use:

- Proxy to Segment CDN (`cdn.segment.com`)
- Proxy to Segment tracking API (`api.segment.io`)
- Proxy to Segment Tracking API (`api.segment.io`)

> warning ""
> If you are using a [Regional Workspace](/docs/guides/regional-segment/#client-side-sources), please note that instead of using `api.segment.io` to proxy the Tracking API, you'll be using `events.eu1.segmentapis.com`
> If you are using a [Regional Workspace](/docs/guides/regional-segment/#client-side-sources), please note that instead of using `api.segment.io` to proxy the Tracking API, you'll be using `events.eu1.segmentapis.com`.

> info ""
> Segment only has the ability to enable the proxy setting for the Web (Analytics.js) source. Details for mobile source proxies are in the [Analytics-iOS](/docs/connections/sources/catalog/libraries/mobile/ios/#proxy-https-calls) and [Analytics-Android](/docs/connections/sources/catalog/libraries/mobile/android/#proxying-http-calls) documentation. It is not currently possible to set up a proxy for server sources using the Segment UI.

> info "Segment loads most integrations through the proxy, except for third-party SDKs"
> Third-party SDKs are loaded by a partner's CDN, even with a Segment proxy configured. For example, if you have a Segment custom proxy enabled and send data to a FullStory destination, FullStory's CDN would load the FullStory SDK.

## Custom Proxy setup
## Custom proxy setup

There are two options you can choose from when you set up your custom domain proxy.
There are two options you can choose from when you set up your custom domain proxy:
1. [CloudFront](#custom-proxy-cloudfront)
2. [Custom CDN or API proxy](#custom-cdn--api-proxy)

Follow the directions listed for [CloudFront](#custom-proxy-cloudfront) or [use your own CDN setup](#custom-cdn--api-proxy). Once you complete those steps and verify that your proxy works for both `cdn.segment.com` and `api.segment.io`, [contact Segment Product Support](https://segment.com/help/contact/) with the following template email:
Follow the directions listed for [CloudFront](#custom-proxy-cloudfront) or [use your own CDN setup](#custom-cdn--api-proxy). Once you complete those steps and verify that your proxy works for both `cdn.segment.com` and `api.segment.io`, [contact Segment Product Support](https://segment.com/help/contact/){:target="_blank"} with the following template email:

```text
Hi,
Expand All @@ -61,7 +61,7 @@ This is {person} from {company}. I would like to configure a proxy for the follo

Double-check the Source URL and the Source ID.

A Segment Customer Success team member will respond that they have enabled this option for your account. When you receive this confirmation, open the source in your workspace, and navigate to Settings > Analytics.js. Update the **Host Address** setting from `api.segment.io/v1` to `[your proxy host]/v1`.
A Segment Customer Success team member will respond that they have enabled this option for your account. When you receive this confirmation, open the source in your workspace, and navigate to **Settings > Analytics.js**. Update the **Host Address** setting from `api.segment.io/v1` to `[your proxy host]/v1`.

> info ""
> The **Host Address** field does not appear in source settings until it's enabled by Segment Customer Success.
Expand Down Expand Up @@ -130,12 +130,12 @@ const analytics = AnalyticsBrowser.load(
)
```

## Custom Proxy CloudFront
## Custom proxy CloudFront

These instructions refer to Amazon CloudFront, but apply more generally to other providers as well. Before changing the Segment Tracking API or the Segment snippet (Segment CDN) to use your new proxy, complete the custom domain proxy setup on your side to avoid any unexpected behavior.

### CDN Proxy
To set up your CDN Proxy:
### CDN proxy
To set up your CDN proxy:
1. Log in to the AWS console and navigate to CloudFront.
2. Click **Create Distribution**.
3. Configure the distribution settings. In the Origin section, update the following values:
Expand Down Expand Up @@ -164,7 +164,7 @@ To add a CNAME record for the Segment proxy to your organizations DNS settings:



### Tracking API Proxy
### Tracking API proxy

As events travel through the proxy before reaching the tracking API, set up a proxy for the tracking API so that all calls proxy through your domain. To do this, set up a CloudFront distribution that's similar to the one in the previous section, with the exception of the Origin Domain Name:

Expand All @@ -188,7 +188,7 @@ These are some common issues that occur for customers implementing a custom prox

#### Cloudflare returning a 403 error

A 403 error can mean that you've misconfigured your Cloudflare CDN distribution. Try one of the following options to fix the error:
A `403` error can mean that you've misconfigured your Cloudflare CDN distribution. Try one of the following options to fix the error:

1. If you have a Cloudflare enterprise plan, create a Page Rule in Cloudflare so that Segment's CDN doesn't refuse the requests made through the Cloudflare Proxy. If `cdn.segment.com` is another CNAME that resolves to `xxx.cloudfront.net`, you will need to use a Page Rule in Cloudflare to override the host header to match the hostname for proxy requests. For more information about overriding the host header, see Cloudflare’s [Rewrite Host headers](https://developers.cloudflare.com/rules/page-rules/how-to/rewrite-host-headers/){:target="_blank”} docs.

Expand All @@ -209,7 +209,7 @@ In order to resolve a CORS OPTIONS pre-request fetch error, you must specify "St

#### CloudFront Proxy returning a 403 error

If your CloudFront Proxy is returing a 403 error, the following change in CloudFront might resolve the issue:
If your CloudFront Proxy is returning a `403` error, the following change in CloudFront might resolve the issue:

```ts
Before:
Expand Down Expand Up @@ -254,9 +254,9 @@ analytics.load({

## Restore the API host to the Segment default

If you wish to restore the proxied API host to it's original value:
1. Navigate to the **Source > Settings > Analytis.js tab**
If you wish to restore the proxied API host to its original value:
1. Navigate to the **Source > Settings > Analytics.js tab**
2. Scroll down until you see the Host address field.
3. Under the field, there is a small blue text that says 'Restore to a default value'. Click **Restore** and then **Save**.

Any changes made to the CDN host must be update manually in your code.
Any changes made to the CDN host must be updated manually in your code.
Loading