diff --git a/src/connections/sources/catalog/libraries/website/javascript/faq.md b/src/connections/sources/catalog/libraries/website/javascript/faq.md index 412e13a699..7b98e57b3d 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/faq.md +++ b/src/connections/sources/catalog/libraries/website/javascript/faq.md @@ -9,16 +9,16 @@ Analytics.js doesn't automatically collect IPv6 addresses. If IPv6 is available ## Is there a size limit on requests? -Yes, the limit is 32KB per event message. Events with a payload larger than 32KB are not accepted by Analytics.js. Segment servers return a 400 response with the error message: `Exceed payload limit`. +Yes, the limit is 32 KB per event message. Events with a payload larger than 32 KB are not accepted by Analytics.js. Segment servers return a 400 response with the error message: `Exceed payload limit`. ## If Analytics.js fails to load, are callbacks not fired? -In the event that Analytics.js does not load, callbacks passed into your API calls do not fire. This is as designed, because the purpose of callbacks are to provide an estimate that the event was delivered and if the library never loads, the events won't be delivered. +In the event that Analytics.js does not load, callbacks passed into your API calls do not fire. This is by design, because the purpose of a callback is to provide an indication that the event was delivered. If the library never loads, the events won't be delivered. ## Is there an updated version of the Segment snippet? Segment released an updated version of the Analytics.js snippet, which introduces several enhancements and fixes that might improve your setup. For a full list of version updates, see the Analytics.js snippet's [Releases](https://github.com/segmentio/snippet/releases){:target="_blank”}. -You can find the latest version of the Segment snippet in your JavaScript source's Overview tab or in the [Quickstart: Analytics.js](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2a-add-the-segment-snippet) documentation. +You can find the latest version of the Segment snippet in your JavaScript source's **Overview** tab or in the [Quickstart: Analytics.js](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2a-add-the-segment-snippet) documentation. While there is no deadline to upgrade your snippet to the latest version, upgrading lets you use the latest improvements in the Segment library. @@ -27,16 +27,16 @@ While there is no deadline to upgrade your snippet to the latest version, upgrad In May 2018, Segment began collecting client-side performance metrics in Analytics.js. This includes metrics like: -- When client side integrations are initialized and when they fail -- When messages are sent to client side integrations and when they fail +- When client-side integrations are initialized and when they fail +- When messages are sent to client-side integrations and when they fail -Segment added these metrics to proactively identify and resolve issues with individual client-side integrations. These metrics are connected to alerts that notify Segment's on-call engineers to take action on these quickly. +Segment added these metrics to proactively identify and resolve issues with individual client-side integrations. These metrics trigger alerts that notify Segment's on-call engineers to take action promptly. There should be no noticeable impact to your data flow. You may notice Analytics.js make an extra network request in the network tab to carry the metrics data to Segment's servers. This extra network request is not made frequently, since the data is sampled and batched every 30 seconds. ## How are properties with `null` and `undefined` values treated? -Segment treats property values set to `null` as null values and drops events set to`undefined`. +Segment treats property values set to `null` as null values and drops events set to `undefined`. For example: @@ -48,6 +48,7 @@ console.log(JSON.stringify({ x: undefined, y: 6 })); // expected output: "{"y":6}" ``` Segment uses the [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify){:target="blank"} method under the hood. + ## Can I overwrite the context fields? Yes. This can be useful if some of these fields contain information you don't want to collect. @@ -65,7 +66,7 @@ analytics.track("Receipt Viewed", {}, { ``` This works for any [context field](/docs/connections/spec/common/#context) that Segment automatically collects. -When working with Page calls, you can overwrite context fields by following the above instructions. However, because the `context.page` fields are also available in the `properties` parameter for page calls, you must also prevent the same fields in the `properties` parameter from being included in your Page call. Use the code in the following example to overwrite `url` available in context field `page.url` and properties parameter: +When working with Page calls, you can overwrite context fields by following the above instructions. However, because the `context.page` fields are also available in the `properties` parameter for Page calls, you must also prevent the same fields in the `properties` parameter from being included in your Page call. Use the code in the following example to overwrite `url` available in context field `page.url` and properties parameter: ```js analytics.page("Receipt Page", { @@ -79,7 +80,7 @@ analytics.page("Receipt Page", { ## Can I add context fields that do not already exist? -Yes. You can add context fields by passing them into the options object as the third argument of the event call. For example, the analytics.js library does not automatically collect location information, but you can add it to the context object. To add location information into the context object, pass it into the third argument as in the following example: +Yes. You can add context fields by passing them into the options object as the third argument of the event call. For example, the Analytics.js library does not automatically collect location information, but you can add it to the context object. To add location information into the context object, pass it into the third argument as in the following example: ```js analytics.track("Order Completed", {}, { @@ -97,7 +98,7 @@ Some destinations accept properties only. As a result, custom context fields you ## What is the impact of exposing the source's write keys? -Segment's library architecture requires you to expose the write key for client-side tracking to work. Other major tools, like Google Analytics, Mixpanel, Kissmetrics, Hubspot, and Marketo, also require you to expose your write key. +Segment's library architecture requires you to expose the write key for client-side tracking to work. Other major tools, like Google Analytics, Mixpanel, Kissmetrics, HubSpot, and Marketo, also require you to expose your write key. If you see any unusual behavior associated with your write key, generate a new key immediately. To generate a new key, navigate to **Connections > Sources** and select your source. On the **Settings** tab, go to the **API Keys** section and click **Generate New Key**. @@ -126,7 +127,7 @@ You'll also need to modify the Segment script with your `nonce` tag, which shoul ## How is the referrer value set? -The Analytics.js library sets the `context.page.referrer` value from the [`window.document.referrer` property](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer){:target="_blank"} set in the browser. If you notice unexpected referrer values reaching Segment, check how this value is being set on your website. +The Analytics.js library sets the `context.page.referrer` value from the [`window.document.referrer` property](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer){:target="_blank"} set in the browser. If you notice unexpected referrer values reaching Segment, check how this value is set on your website. ## Are there any rate limits in place for the CDN settings endpoint? @@ -142,4 +143,4 @@ If you need this functionality, you have a couple of options: **Use a third-party API**: Alternatively, you can use third-party services like Geolocation API to convert IP addresses to geolocation data. Afterward, you can pass this information as a trait in Identify calls or as a property in Track calls to Segment. This allows you to manage geolocation data according to your specific needs, though it will likely require engineering resources. ## Why is my payload populating incorrectly? -Payload parameters aren't populated in a guaranteed order. Your payload should still be ingested as long as all necessary parameters are included. +Payload parameters aren't populated in a guaranteed order. Your payload will still be ingested as long as all necessary parameters are included. diff --git a/src/connections/sources/catalog/libraries/website/javascript/identity.md b/src/connections/sources/catalog/libraries/website/javascript/identity.md index 7f57aa9c60..884cb96b3e 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/identity.md +++ b/src/connections/sources/catalog/libraries/website/javascript/identity.md @@ -3,11 +3,11 @@ title: Managing identity in Analytics.js strat: ajs --- -This page explains how Analytics.js identifies users, and passes userID and anonymousID data, and how to override and change this information. +This page explains how Analytics.js identifies users, passes `userID` and `anonymousID` data, and how to override and change this information. -## Segment ID Persistence +## Segment ID persistence -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 meant 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 that as the Segment ID on the cookie whenever possible. Local storage is meant for storing this type of 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, 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` when they next visit the page. @@ -30,8 +30,8 @@ Example: ajs_anonymous_id=%2239ee7ea5-b6d8-4174-b612-04e1ef3fa952 ``` -You can override the default-generated anonymousID in code using the methods described below: -- [Set anonymousId from the Segment snippet](#override-the-anonymous-id-from-the-segment-snippet) (before the `ready` method returns) +You can override the default-generated `anonymousID` in code using the methods described below: +- [Set anonymousId from the Segment snippet](#override-the-anonymous-id-from-the-segment-snippet) (before the Ready method returns) - [Use a call to override the anonymousID](#override-the-default-anonymous-id-with-a-call) - [Set `anonymousId` in the `options` object of a call](#override-the-anonymous-id-using-the-options-object) @@ -43,9 +43,9 @@ You can get the user's current `anonymousId` using the following call: analytics.user().anonymousId(); ``` -If the user's `anonymousId` is `null` (meaning not set) when you call this function, Analytics.js automatically generated and sets a new `anonymousId` for the user. +If the user's `anonymousId` is `null` (meaning not set) when you call this function, Analytics.js automatically generates and sets a new `anonymousId` for the user. -If you are using the npm library, the previous call returns a promise for `user()`. As a workaround, you'll need to grab the user's current `anonymousId` in the following way: +If you're using the npm library, the previous call returns a promise for `user()`. As a workaround, you'll need to grab the user's current `anonymousId` in the following way: ```js analytics.instance?.user().anonymousId() @@ -57,13 +57,13 @@ A user's `anonymousId` changes when any of the following conditions are met. - The user clears their cookies _and_ `localstorage`. - Your site or app calls [`analytics.reset()`](/docs/connections/sources/catalog/libraries/website/javascript/#reset-or-logout) during in the user's browser session. -- Your site or app calls `analytics.identify()` with a userId that is different from the current userId. -- Your site or app is setting `ajs_user_id` to an empty string or calling `analytics.user().id('')` before calling `analytics.identify()`. This sequence of events will result in a new anonymousId being set when `analytics.identify()` is called. +- Your site or app calls `analytics.identify()` with a `userId` that is different from the current `userId`. +- Your site or app is setting `ajs_user_id` to an empty string or calling `analytics.user().id('')` before calling `analytics.identify()`. This sequence of events will result in a new `anonymousId` being set when `analytics.identify()` is called. ### Override the Anonymous ID from the Segment snippet -You can also set the `anonymousId` immediately inside your Segment snippet, even before the `ready` method returns. +You can also set the `anonymousId` immediately inside your Segment snippet, even before the Ready method returns. ```js analytics.load('writekey'); @@ -71,14 +71,14 @@ You can also set the `anonymousId` immediately inside your Segment snippet, even analytics.setAnonymousId('ABC-123-XYZ'); ``` -Use this method if you are queueing calls before `ready` returns and they require a custom `anonymousId`. Keep in mind that setting the `anonymousId` in Analytics.js does not overwrite the anonymous tracking IDs for any destinations you're using. +Use this method if you are queueing calls before Ready returns and they require a custom `anonymousId`. Keep in mind that setting the `anonymousId` in Analytics.js does not overwrite the anonymous tracking IDs for any destinations you're using. > info "" -> Device-mode destinations that load their code on your site _might_ also set their own anonymous ID for the user that is separate and different from the Segment generated one. Some destinations use the Segment `anonymousId`. Read the documentation for each Destination to find out if a Destination sets its own ID. +> Device-mode destinations that load their code on your site _might_ also set their own anonymous ID for the user that is separate and different from the Segment generated one. Some destinations use the Segment `anonymousId`. Read the documentation for each destination to find out if a destination sets its own ID. ### Override the default Anonymous ID with a call -If the default generated UUID does not meet your needs, you can override it `anonymousId` for the current user using either of the following methods. +If the default generated UUID does not meet your needs, you can override the `anonymousId` for the current user with either of the following methods: ```js analytics.user().anonymousId('ABC-123-XYZ'); @@ -92,17 +92,19 @@ These methods behave exactly the same. ### Override the Anonymous ID using the options object -Or in the `options` object of [`identify`](/docs/connections/spec/identify/), [`page`](/docs/connections/spec/page/), or [`track`](/docs/connections/spec/track/) calls, like this: +You can override the `anonymousID` in the `options` object of [Identify](/docs/connections/spec/identify/), [Page](/docs/connections/spec/page/), or [Track](/docs/connections/spec/track/) calls, like this: -Set the anonymousId in the Options object using the format in the following examples. +Set the `anonymousId` in the `options` object using the format in the following examples. -The custom anonymousId persists when you use these methods, even if you do not explicitly specify the anonymousId in the calls. +The custom `anonymousId` persists when you use these methods, even if you do not explicitly specify the `anonymousId` in the calls. -For example, after the Track call below sets the anonId, any later track calls from this user will have the anonymousId of `ABC-123-XYZ`, even if it is not explicitly specified in the track call. +For example, after a Track call sets the `anonymousID` to `ABC-123-XYZ`, any additional Track calls from this user will have the same `anonymousId`, even if it's not explicitly specified in the Track call. #### Override anonymousId in an Identify call +You can override `anonymousID` with an Identify call. For example: + ```js analytics.identify('user_123', { name: 'Jane Kim' @@ -113,12 +115,16 @@ analytics.identify('user_123', { #### Override anonymousId on a Page call +You can override `anonymousID` with a Page call. For example: + ```js analytics.page({}, { anonymousId: 'ABC-123-XYZ' }); ``` #### Override anonymousId on a Track call +You can override `anonymousID` with a Track call. For example: + ```js analytics.track('Email Clicked', { callToAction: 'Signup' @@ -146,7 +152,7 @@ Consider this Identify event: ```js analytics.identify('12091906-01011992', { plan_id: 'Paid, Tier 2', - email: 'grace@usnavy.gov' + email: 'grace@example.com' }); ``` @@ -166,7 +172,7 @@ analytics.track('Clicked Email', { ); ``` -This appends the `plan_id` trait to this Track event. This does _not_ add the name or email, since those traits were not added to the `context` object. You must do this for every following event you want these traits to appear on, as the `traits` object does not persist between calls. +This appends the `plan_id` trait to the Track event. This does _not_ add the name or email, since those traits were not added to the `context` object. You must do this for every following event you want these traits to appear on, as the `traits` object does not persist between calls. By default, non-Identify events (like Track or Page) **don't automatically collect user traits** from previous Identify calls. To include traits from an `identify()` event in later events, you'll need to add them manually to the `context.traits` object within the `options` parameter. @@ -180,9 +186,9 @@ Each Analytics.js method has an `options` parameter where you can pass the `cont Adding traits to events is especially useful if you're using [Actions destinations](/docs/connections/destinations/actions/), since it makes those traits available for mapping in the destination’s configuration. -## Clearing Traits +## Clearing traits -You can pass an empty object to the `traits` object to clear _all_ cached traits for a User or Group. +You can pass an empty object to the `traits` object to clear _all_ cached traits for a user or group. Traits are cached by default when you call the Identify and Group methods. You can clear the `traits` object for the user or group by passing `traits` an empty object: @@ -195,13 +201,13 @@ analytics.group().traits({}); ## Using analytics.user() and analytics.group() -You can use the `user` or `group` method as soon as the Analytics.js library loads, to return information about the currently identified user or group. This information is retrieved from the user's cookie. +You can use the User or Group method as soon as the Analytics.js library loads, to return information about the currently identified user or group. This information is retrieved from the user's cookie. > success "" -> **Tip:** You can wrap any reference to `user()` or `group()` in a [ready function block](/docs/connections/sources/catalog/libraries/website/javascript#ready) to ensure that Analytics.js has fully loaded so these methods are available. +> You can wrap any reference to `user()` or `group()` in a [ready function block](/docs/connections/sources/catalog/libraries/website/javascript#ready) to ensure that Analytics.js has fully loaded so these methods are available. Examples: @@ -228,7 +234,7 @@ analytics.ready(function() { ## Anonymizing IP -Segment automatically collects the user's IP address for device-based (iOS, Android, Analytics.js and Xamarin) events. +Segment automatically collects the user's IP address for device-based (iOS, Android, Analytics.js, and Xamarin) events. > info "IPv6" > At the moment, Segment doesn't support automatically collecting IPv6 addresses. diff --git a/src/connections/sources/catalog/libraries/website/javascript/middleware.md b/src/connections/sources/catalog/libraries/website/javascript/middleware.md index 340ada5a66..9be9c62b4c 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/middleware.md +++ b/src/connections/sources/catalog/libraries/website/javascript/middleware.md @@ -4,21 +4,21 @@ strat: ajs --- -Middlewares allow developers to extend Analytics.js with custom code which runs on every event. This code has full access to the DOM and Browser API, and helps customers enrich and transform event payloads. Source Middlewares and Destination Middlewares are available on the Analytics.js snippet version `4.12.0` and later. +Middlewares allow developers to extend Analytics.js with custom code that runs on every event. This code has full access to the DOM and Browser API, and helps customers enrich and transform event payloads. Source and destination middlewares are available on the Analytics.js snippet version `4.12.0` and later. -Analytics.js can be extended using two functions: +Analytics.js can be extended using 2 functions: ```js addSourceMiddleware(middleware) addDestinationMiddleware(targetIntegration, middleware1, middleware2, ...) ``` -The first function (Source Middleware) allows you to manipulate the payload and filter events on a per-source basis, while the second function (Destination Middleware) allows this on a per destination basis. Middlewares run in the browser. +The first function (source middleware) allows you to manipulate the payload and filter events on a per-source basis, while the second function (destination middleware) allows this on a per destination basis. Middlewares run in the browser. > info "" -> **Note**: Destination-middleware only act on [data sent to destinations in device-mode](/docs/connections/destinations#connection-modes). Since the destination middleware code exists in your app or project, it cannot transform the data sent from the Segment servers to the destination endpoint. +> Destination-middleware only act on [data sent to destinations in device-mode](/docs/connections/destinations#connection-modes). Since the destination middleware code exists in your app or project, it cannot transform the data sent from the Segment servers to the destination endpoint. -## Using Source Middlewares +## Using source middlewares To add source middleware, use the following API: @@ -26,12 +26,11 @@ To add source middleware, use the following API: analytics.addSourceMiddleware(({ payload, next, integrations }) => .... ) ``` -- `payload` represents the event payload sent by Analytics.js. To change the value of the `payload`, mutate the `payload.obj` object. (See the example below.) +- `payload` represents the event payload sent by Analytics.js. To change the value of the `payload`, mutate the `payload.obj` object, as in the example below. - `next` represents the next function to be called in the source middleware chain. If the middleware provided does not call this function, the event is dropped on the client and is not delivered to Segment or any destinations. -- `integrations` is an array of objects representing all the integrations that the payload is sent to. If an integration in this array is set to a ‘falsey' value then the event is not be sent to the Integration. +- `integrations` is an array of objects representing all the integrations that the payload is sent to. If an integration in this array is set to a falsy value, then the event is not sent to the integration. -### Examples -#### Modifying an event +#### Example: Modifying an event ```js analytics.addSourceMiddleware(({ payload, next }) => { const { event } = payload.obj.context @@ -42,7 +41,7 @@ analytics.addSourceMiddleware(({ payload, next }) => { }); ``` -#### Dropping an event +#### Example: Dropping an event ```js analytics.addSourceMiddleware(({ payload, next }) => { const { event } = payload.obj.context @@ -53,7 +52,7 @@ analytics.addSourceMiddleware(({ payload, next }) => { }); ``` -## Using Destination Middlewares +## Using destination middlewares To add destination middleware, use the following API: @@ -62,7 +61,7 @@ To add destination middleware, use the following API: analytics.addDestinationMiddleware('integrationA', ({ payload, next, integration }) => .... ) ``` -- `payload` represents the event payload sent by Analytics.js. To change the value of the `payload`, mutate the `payload.obj` object. (See the example below.) +- `payload` represents the event payload sent by Analytics.js. To change the value of the `payload`, mutate the `payload.obj` object, as in the example below. - `next` represents the next function to be called in the destination middleware chain. If the middleware provided does not call this function, then the event is dropped completely for the given destination. - `integration` is a string value representing the integration that this middleware is applied to. To apply middleware to all destinations (excluding Segment.io), you can use the `*` value. @@ -87,11 +86,11 @@ analytics.addDestinationMiddleware('integrationA', ({ payload, next, integration > info "" -> **Note**: Destination-middleware only act on [data sent to destinations in device-mode](/docs/connections/destinations#connection-modes). Since the destination middleware code exists in your app or project, it cannot transform the data sent from the Segment servers to the destination endpoint. +> Destination middleware only act on [data sent to destinations in device-mode](/docs/connections/destinations#connection-modes). Since the destination middleware code exists in your app or project, it cannot transform the data sent from the Segment servers to the destination endpoint. ## Adding middlewares to Analytics.js -The above defined Source & Destination Middleware can be added to the Analytics.js execution chain as: +The above defined source and destination middleware can be added to the Analytics.js execution chain as: ```js analytics.addSourceMiddleware(() => ...); @@ -99,17 +98,17 @@ analytics.addDestinationMiddleware('integrationA', () => ...); ``` -You can call the `.addSourceMiddleware(fn)` multiple times, and the order of operations reflects the order in which you register your Source Middleware. +You can call the `.addSourceMiddleware(fn)` multiple times, and the order of operations reflects the order in which you register your source middleware. Both `.addSourceMiddleware(fn)` and `.addDestinationMiddleware('integration', fn, ...)` can be called before [`.load()`](/docs/connections/sources/catalog/libraries/website/javascript/#load-options). -## Braze Middleware +## Braze middleware -If you use the Braze (Appboy) destination in either [cloud or device mode](/docs/connections/destinations/#connection-modes) you can save Braze costs by "debouncing" duplicate `identify()` calls from Segment by adding our [open-source Middleware tool](https://github.com/segmentio/segment-braze-mobile-middleware) to your implementation. +If you use the Braze (Appboy) destination in either [cloud or device mode](/docs/connections/destinations/#connection-modes) you can reduce Braze costs by debouncing duplicate Identify calls from Segment. You can achieve this by adding Segment's [open-source middleware tool](https://github.com/segmentio/segment-braze-mobile-middleware){:target="_blank"} to your implementation. This optional middleware is disabled by default. When enabled, it ensures that only events where at least one changed trait value are sent to Braze, and events with duplicate traits are not sent. -To enable this Middleware for a JavaScript or Project source, go to `Analytics.js` in your source settings. +To enable this middleware for a JavaScript or Project source, go to **Analytics.js** in your source settings. ![BrazeMiddleware](images/sources_ajs_brazemiddleware.png) -More information about this tool and how it works [is available in the project's README](https://github.com/segmentio/segment-braze-mobile-middleware/blob/master/README.md#how-does-this-work). +More information about this tool and how it works is available in the project's [README](https://github.com/segmentio/segment-braze-mobile-middleware/blob/master/README.md#how-does-this-work){:target="_blank"}. diff --git a/src/connections/sources/catalog/libraries/website/javascript/querystring.md b/src/connections/sources/catalog/libraries/website/javascript/querystring.md index f105be3f82..445a787eff 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/querystring.md +++ b/src/connections/sources/catalog/libraries/website/javascript/querystring.md @@ -15,13 +15,12 @@ Here are the *optional* query parameters to use: | `ajs_prop_` | A property to pass to the Track call. | This won't implicitly trigger an event and is dependent on you also passing `ajs_event`. This property is included in the resulting Track call. | | `ajs_trait_` | A trait to pass to the Identify call. | This won't implicitly trigger any call and is dependent on you also passing `ajs_uid`. This trait is included in the resulting Identify call. | -For example, this URL: +For example, this URL creates the following events on the page: ```text http://segment.com/?ajs_uid=123456789abcd&ajs_event=Clicked%20Email&ajs_aid=abc123&ajs_prop_emailCampaign=First+Touch&ajs_trait_name=Karl+Jr. ``` - -would create the following events on the page. +Each trigger parameter is optional. You can pass up to **1 of each trigger parameter**, as shown in the following example: ```js analytics.identify('123456789abcd', { name: 'Karl Jr.' }); @@ -29,7 +28,7 @@ analytics.track('Clicked Email', { 'emailCampaign': 'First Touch' }); analytics.user().anonymousId('abc123'); ``` -Each trigger parameter is optional. You can pass up to **one of each trigger parameter** as shown in the example above. + ## How can I control query string processing? @@ -47,13 +46,13 @@ You can also keep query string processing on, but enforce validation rules. For ```js analytics.load('', { useQueryString: { - // set a pattern for anonymous id + // set a pattern for anonymousId aid: /([A-Z]{10})/, - // set a pattern for user id + // set a pattern for userId uid: /([A-Z]{6})/ } }) ``` > info "" -> The `useQueryString` option is **only** available when you load analytics.js through the [NPM package](https://www.npmjs.com/package/@segment/analytics-next){:target="_blank"}. +> The `useQueryString` option is **only** available when you load Analytics.js through the [npm package](https://www.npmjs.com/package/@segment/analytics-next){:target="_blank"}. diff --git a/src/connections/sources/catalog/libraries/website/javascript/single-page-apps.md b/src/connections/sources/catalog/libraries/website/javascript/single-page-apps.md index 42a8fbd546..5339bba4c2 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/single-page-apps.md +++ b/src/connections/sources/catalog/libraries/website/javascript/single-page-apps.md @@ -3,13 +3,13 @@ title: Single Page Applications strat: ajs --- -While Single Page Apps (SPAs) are great for many reasons, they do require some extra consideration in order to set up client-side tracking than with a traditional webpage. +While Single Page Apps (SPAs) offer many benefits, setting up client-side tracking requires extra consideration compared to traditional web pages. -By default, the Segment analytics.js library doesn’t generate or store the referrer value. Instead, the referrer value you see in the payload is the value returned by `document.referrer` directly from the browser, and the URL value is the canonical URL on the page. +By default, the Segment Analytics.js library doesn’t generate or store the referrer value. Instead, the `referrer` value you see in the payload is the value returned by `document.referrer` directly from the browser, and the `url` value is the canonical URL on the page. -When a user navigates between pages on an SPA website, there won’t be a referrer because there is no concept of a new page since it’s all a single page load. This means that the referrer will always be the same as it was on the first page call where someone was first directed to your site. However, in order to circumvent this, you can manually set the referrer and URL in your Segment calls by updating the context object. +When a user navigates between pages on an SPA website, there won’t be a referrer because there is no concept of a new page since it’s all a single page load. This means that the referrer will always be the same as it was on the first page call where someone was first directed to your site. However, in order to circumvent this, you can manually set the `referrer` and `url` values in your Segment calls by updating the context object. -For example, a Page call with the referrer and URL manually set looks like this: +For example, a Page call with the `referrer` and `url` manually set looks like this: ```js analytics.page({ @@ -29,20 +29,20 @@ analytics.track('Example Event', {}, {page: { ## Tracking emulated page views -Your application should update the URL in the address bar to emulate traditional webpage navigation. Full page requests aren't made in most of these instances since the resources are loaded on initial page load. This means that the Page call in the traditional analytics.js snippet won't fire again as a user navigates around your site. +Your application should update the URL in the address bar to emulate traditional webpage navigation. Full page requests aren't made in most of these instances since the resources are loaded on initial page load. This means that the Page call in the traditional Analytics.js snippet won't fire again as a user navigates around your site. -You should still place the snippet in the head of your site, but you should remove the Page call and fire it whenever you're emulating a page load. Segment recommends that you call [Page](/docs/connections/sources/catalog/libraries/website/javascript/#page) from the same block of logic that updates the view and URL path like below: +You should still place the snippet in the `` of your site, but you should remove the Page call and fire it whenever you're emulating a page load. Segment recommends that you call [Page](/docs/connections/sources/catalog/libraries/website/javascript/#page) from the same block of logic that updates the view and URL path, as shown below: ```js // The new view has been called to render analytics.page("Home") ``` -To track more than the page field, pass those fields in as additional properties. Segment recommends that you use variables to set information about page properties, rather than hard-coding. In most SPA frameworks, you can automate this by attaching the Page call to the routing service. +To track more than the page field, pass those fields in as additional properties. Segment recommends that you use variables to set information about page properties, rather than hardcoding them. In most SPA frameworks, you can automate this by attaching the Page call to the routing service. ## What to do with code that lives in the analytics.ready() function? -Analytics.js ships with a function called analytics.ready() which lets you make calls to the native integrations that Segment loads for you before they actually initialize. For instance, this is where you could choose to load a live chat widget only for users that you haven't yet identified with a userId. +Analytics.js ships with a function called `analytics.ready()` which lets you make calls to the native integrations that Segment loads for you before they actually initialize. For instance, this is where you could choose to load a live chat widget only for users that you haven't yet identified with a `userId`. Since the code in the head of your website is executed only on initial page load or a refresh, you can still make calls to those native tools, but they won't run on each emulated page view. diff --git a/src/connections/sources/catalog/libraries/website/javascript/troubleshooting.md b/src/connections/sources/catalog/libraries/website/javascript/troubleshooting.md index d78145e23f..7cdf4f4312 100644 --- a/src/connections/sources/catalog/libraries/website/javascript/troubleshooting.md +++ b/src/connections/sources/catalog/libraries/website/javascript/troubleshooting.md @@ -3,26 +3,28 @@ title: Troubleshooting Analytics.js strat: ajs --- -The console reveals all. [Learn how to access the JavaScript console in each browser](#how-do-i-open-the-javascript-console-in-your-debugger). -Any Analytics.js methods may be executed manually. Use the Network tab to inspect requests. +To help you troubleshoot common issues when implementing Analytics.js, this page covers steps to verify your implementation, resolve errors, and ensure that data correctly flows to your destinations. + +> info "" +> You can manually execute any Analytics.js methods. Use the **Network** tab to inspect requests. [Learn how to access the JavaScript console in each browser](#how-do-i-open-the-javascript-console-in-your-debugger). ## Are you loading Analytics.js? -Open the JavaScript console and enter `analytics`. Does it return an object, as seen below? +Open the JavaScript console and enter `analytics`. If it returns an object, as shown below, then you're successfully loading Analytics.js onto your website. ![Returning analytics object](images/VOsmoAB.gif) -The object means that you are successfully loading Analytics.js onto your website. If you get an `undefined` error, Analytics.js is not loading successfully: +If you get an `undefined` error, Analytics.js is not loading successfully: ![Returning analytics object error](images/CFsktto.gif) Segment also provides a Chrome web extension, [Segment Inspector](/docs/connections/sources/catalog/libraries/website/javascript/index.html#segment-inspector), which you can use to validate that you're successfully loading Analytics.js. -Solution: [Follow the Analytics.js Quickstart Guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/) +To learn more, follow the [Analytics.js Quickstart Guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/). ## Are you loading two instances of Analytics.js? -Note that you *cannot* load Analytics.js twice on the same page, even if you're using different write keys. You might encounter `Uncaught RangeError: Maximum call stack size exceeded`. You can conditionally set the write key based on an environment variable. +Note that you *cannot* load Analytics.js twice on the same page, even if you're using different write keys. If you do, you might encounter `Uncaught RangeError: Maximum call stack size exceeded`. Instead, you can conditionally set the write key based on an environment variable. Example: ```js @@ -34,27 +36,27 @@ ENV === 'production' ? writeKey = 'A' : writeKey = 'B'; The error can occur for different reasons: -* Snippet syntax: Ensure you correctly added the Segment snippet to the page. Check for any missing or extra characters. Follow [this guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2-install-segment-to-your-site). +- Snippet syntax: Ensure you correctly added the Segment snippet to the page. Check for any missing or extra characters. Follow [this guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2-install-segment-to-your-site). -* NPM package: If you're using Segment through NPM, refer to [this guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2b-install-segment-as-a-npm-package). +- npm package: If you're using Segment through npm, refer to [this guide](/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2b-install-segment-as-a-npm-package). -* Browser cache: Clear the browser cache, as this is a common cause for `ChunkLoadError`. +- Browser cache: Clear the browser cache, as this is a common cause for `ChunkLoadError`. -* Cloudflare caching: If you use Cloudflare to proxy Segment, disable caching for the Segment JS file. +- Cloudflare caching: If you use Cloudflare to proxy Segment, disable caching for the Segment JS file. ## Do you see events appear in your debugger? -When you reload the page, does your debugger show a new [`page`](/docs/connections/spec/page)? You can also check the JavaScript console in the browser and manually fire an event, like an Identify call, which would show up in the debugger. +When you reload the page, does your debugger show a new [Page call](/docs/connections/spec/page)? You can also check the JavaScript console in the browser and manually fire an event, like an Identify call, which would show up in the debugger. -- You can also use [Segment's Chrome extension](/docs/connections/sources/catalog/libraries/website/javascript/index.html#segment-inspector)to inspect events. +- You can use [Segment's Chrome extension](/docs/connections/sources/catalog/libraries/website/javascript/index.html#segment-inspector) to inspect events. -![Making an identify call](images/7Ymnh2S.gif) +![Making an Identify call](images/7Ymnh2S.gif) -If the call doesn't appear in the debugger, open up the JavaScript console and check the Network tab to see if the outbound web services requests are being initiated: +If the call doesn't appear in the debugger, open the JavaScript console and check the **Network** tab to see if the outbound web services requests are being initiated: ![Checking for calls in the network tab](images/d8CmIY2.png) -In the above, the `p` is a [`page`](/docs/connections/spec/page) call and the `i` is an [`identify`](/docs/connections/spec/identify) call. If you don't at least see the `p`, then check if you are loading Analytics.js correctly. +In the above, the `p` is a [Page](/docs/connections/spec/page) call and the `i` is an [Identify](/docs/connections/spec/identify) call. If you don't at least see the `p`, verify that you are loading Analytics.js correctly. ## Using the Segment Chrome extension to validate your implementation @@ -65,18 +67,18 @@ The [Segment Inspector](/docs/connections/sources/catalog/libraries/website/java Some destinations send data directly from the website to their servers. You can check the Network tab in your JavaScript console to see the outbound web services requests being initiated. -In the image below, with Google Analytics as an example, the `page` call forms an outbound request that looks like this: +Using Google Analytics as an example, the Page call forms an outbound request that looks like this: ![Google Analytics outbound request](images/CBdS5dO.png) -If this outbound request is not showing up in the network when you fire an `identify` call, then check the following: +If this outbound request is not showing up in the network when you fire an Identify call, then view the following sections for more troubleshooting steps. -## Is your web site deployed under a domain on the Public Suffix List? +## Is your website deployed under a domain on the Public Suffix List? The [Public Suffix List](https://publicsuffix.org/list/){:target="blank"} is a catalog of certain Internet effective top-level domains, enumerating all domain suffixes controlled by registrars. -The implications of these domain suffixes is that first party cookies cannot be set on them. Meaning, `foo.example.co.uk` can share cookie access with `bar.example.co.uk`, but `example.co.uk` should be walled off from cookies at `example2.co.uk`. The latter two domains could be registered by different owners. +The implications of these domain suffixes are that first party cookies cannot be set on them. Meaning, `foo.example.co.uk` can share cookie access with `bar.example.co.uk`, but `example.co.uk` should be walled off from cookies at `example2.co.uk`. The latter two domains could be registered by different owners. Examples of domains on the Public Suffix List that are common in troubleshooting include: @@ -97,13 +99,13 @@ The JavaScript console reveals all requests, outbound and inbound, to your brows Alternatively, Segment provides the [Segment Inspector](/docs/connections/sources/catalog/libraries/website/javascript/index.html#segment-inspector), a Chrome web extension designed to enable debugging of your Segment integration in web applications that are instrumented with Analytics.js. -## Analytics.js failing to load due to Ad Blockers or Browser Privacy Settings +## Analytics.js failing to load due to ad blockers or browser privacy settings Segment advises against circumventing tracking blockers or browser privacy settings for client-side tracking. The user has ultimate control as to what gets loaded on the page. Segment acknowledges that this can result in some data loss in client-side tracking and suggests [workarounds](/docs/connections/sources/catalog/libraries/website/javascript/index.html#tracking-blockers-and-browser-privacy-settings) to address this issue. -## Analytics.js and Destinations not tracking query string parameters on certain Safari iOS and MacOS Versions +## Analytics.js and destinations not tracking query string parameters on certain Safari iOS and macOS versions -Due to updates in certain Safari iOS and MacOS versions, Segment's Analytics.js and Destinations tools might experience limitations in capturing query string parameters. As a result, you may notice some events missing campaign information. +Due to updates in certain Safari iOS and macOS versions, Segment's Analytics.js and destinations tools might experience limitations in capturing query string parameters. As a result, you may notice some events missing campaign information. ## Why am I seeing a "SameSite" warning? @@ -111,18 +113,18 @@ Due to updates in certain Safari iOS and MacOS versions, Segment's Analytics.js If you see a warning like the following, it could have one of several causes: "A cookie associated with a cross-site resource at http://segment.com/ was set without the `SameSite` attribute [...]" -Segment correctly sets cookies with the 'SameSite' attribute with Analytics.js. +Segment correctly sets cookies with the `SameSite` attribute with Analytics.js. -If you see this warning, it is because you previously visited http://segment.com, and are getting the warning due to unrelated cookies. To verify that this is the issue, visit your page in Incognito Mode and confirm that the warning no longer occurs. Your users won't see this warning unless they _also_ visited http://segment.com. +If you see this warning, it's because you previously visited http://segment.com, and are getting the warning due to unrelated cookies. To verify that this is the issue, visit your page in Incognito Mode and confirm that the warning no longer occurs. Your users won't see this warning unless they _also_ visited http://segment.com. ## Why am I seeing additional cookies on my website? -The AJS cookies being set under segment.com are first-party cookies. They are part of Segment's own implementation as well as the destination Segment uses. These cookies are not related to your implementation of Segment, and you only see them because you've visited Segment's domain using the same browser. They are sent to the writekey connected to Segment's own workspace, and are associated with the events Segment tracks when you visit segment.com. +The Analytics.js cookies being set under segment.com are first-party cookies. They are part of Segment's own implementation as well as the destination Segment uses. These cookies are not related to your implementation of Segment, and you only see them because you've visited Segment's domain using the same browser. They are sent to the writekey connected to Segment's own workspace, and are associated with the events Segment tracks when you visit segment.com. -### Known Incompatibilities with Prototype.js +### Known incompatibilities with Prototype.js -If you're having issues with your destinations loading with Prototype.js, there is a [known issue that was reported](https://github.com/prototypejs/prototype/issues/338){:target="_blank"} regarding this. In order to prevent the issues, you can preserve the original `Array.from` method without letting the prototype override it. +If you're having issues with your destinations loading with Prototype.js, there is a [known issue that was reported](https://github.com/prototypejs/prototype/issues/338){:target="_blank"} regarding this. In order to prevent the issue, you can preserve the original `Array.from` method without letting the prototype override it. ## Why am I getting an empty campaign object in my event payload? @@ -133,6 +135,8 @@ Analytics.js generates a campaign object inside the context object whenever the You may see events with timestamp discrepancies due to manual overriding of the timestamp value, mobile apps closed or set in the background, traffic from bots, or inaccurate device or browser time. For more information, see Segment's [Common Fields Spec](/docs/connections/spec/common/#why-are-events-received-with-timestamps-set-in-the-past-or-future). -## Known issues: +## View additional known issues + +You can review other known Analytics.js issues on [GitHub](https://github.com/segmentio/analytics.js/issues). + -[Review and contribute to these on GitHub](https://github.com/segmentio/analytics.js/issues).