Skip to content

Commit ae8b7e1

Browse files
authored
Merge pull request #7829 from segmentio/master
`master` into `develop`
2 parents 0ddedd1 + 7d8c76f commit ae8b7e1

File tree

1 file changed

+248
-62
lines changed

1 file changed

+248
-62
lines changed

src/connections/auto-instrumentation/web-setup.md

Lines changed: 248 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ hidden: true
55

66
This guide outlines the steps required to set up the Signals SDK in your JavaScript website.
77

8-
You'll learn how to add Auto-Instrumentation sources, integrate dependencies, and ensure that your setup captures and processes data as intended.
8+
You'll learn how to add Auto-Instrumentation sources, integrate dependencies, and ensure that your setup captures and processes data as intended.
99

1010
> info "Auto-Instrumentation Private Beta"
1111
> Auto-Instrumentation is currently in Private Beta and is governed by Segment's [First Access and Beta Preview Terms](https://www.twilio.com/en-us/legal/tos){:target="_blank"}. Segment is actively iterating on and improving the Auto-Instrumentation user experience.
@@ -15,53 +15,180 @@ You'll learn how to add Auto-Instrumentation sources, integrate dependencies, an
1515
1616
## Step 1: Add a source and get its write key
1717

18-
You'll first need to add a source and copy its write key:
18+
You'll first need to add a source and copy its write key:
1919

2020
1. In your Segment workspace, navigate to **Connections > Auto-Instrumentation** and click **Add source**.
2121
2. Select a source, give the source a name, and click **Save**.
22-
3. Return to **Connections > Sources** to view your sources.
22+
3. Return to **Connections > Sources** to view your sources.
2323
4. In the **My sources** table, find and click the new source you just set up.
24-
5. In the **Initialize the Client** section, look for and copy the `writeKey` displayed in the code block.
24+
5. In the **Initialize the Client** section, look for and copy the `writeKey` displayed in the code block.
2525

2626
## Step 2: Add dependencies and initialization code
2727

28-
Next, you'll need to add the Signals SDKs to your web environment.
28+
Next, you'll need to add the Signals SDKs to your web environment.
29+
30+
Choose the installation method that matches your setup:
31+
32+
- **Option A:** For websites loading Segment through the HTML snippet.
33+
- **Option B:** For projects using npm, yarn, or pnpm.
34+
35+
### Option A: Websites using the Segment snippet (HTML)
36+
37+
> warning ""
38+
> Include only one Segment snippet per page. Replacing your existing snippet prevents duplicate `analytics.load()` calls.
39+
40+
If your site uses the standard Segment snippet, **replace it** with the following version, which includes the Signals SDK:
41+
42+
```html
43+
<head>
44+
<title>My Website</title>
45+
<!-- Replace <YOUR_WRITE_KEY> in 'data-segment-write-key' -->
46+
<script data-segment-write-key="<YOUR_WRITE_KEY>">
47+
!(function () {
48+
var i = "analytics",
49+
analytics = (window[i] = window[i] || []);
50+
if (!analytics.initialize)
51+
if (analytics.invoked)
52+
window.console &&
53+
console.error &&
54+
console.error("Segment snippet included twice.");
55+
else {
56+
analytics.invoked = !0;
57+
analytics.methods = [
58+
"trackSubmit",
59+
"trackClick",
60+
"trackLink",
61+
"trackForm",
62+
"pageview",
63+
"identify",
64+
"reset",
65+
"group",
66+
"track",
67+
"ready",
68+
"alias",
69+
"debug",
70+
"page",
71+
"screen",
72+
"once",
73+
"off",
74+
"on",
75+
"addSourceMiddleware",
76+
"addIntegrationMiddleware",
77+
"setAnonymousId",
78+
"addDestinationMiddleware",
79+
"register",
80+
];
81+
analytics.factory = function (e) {
82+
return function () {
83+
if (window[i].initialized)
84+
return window[i][e].apply(window[i], arguments);
85+
var n = Array.prototype.slice.call(arguments);
86+
if (
87+
[
88+
"track",
89+
"screen",
90+
"alias",
91+
"group",
92+
"page",
93+
"identify",
94+
].indexOf(e) > -1
95+
) {
96+
var c = document.querySelector("link[rel='canonical']");
97+
n.push({
98+
__t: "bpc",
99+
c: (c && c.getAttribute("href")) || void 0,
100+
p: location.pathname,
101+
u: location.href,
102+
s: location.search,
103+
t: document.title,
104+
r: document.referrer,
105+
});
106+
}
107+
n.unshift(e);
108+
analytics.push(n);
109+
return analytics;
110+
};
111+
};
112+
for (var n = 0; n < analytics.methods.length; n++) {
113+
var key = analytics.methods[n];
114+
analytics[key] = analytics.factory(key);
115+
}
116+
analytics._writeKey = document.currentScript.getAttribute("data-segment-write-key");
117+
118+
var r = document.getElementsByTagName("script")[0];
119+
analytics.load = function (key, n) {
120+
var t = document.createElement("script");
121+
t.type = "text/javascript";
122+
t.async = !0;
123+
t.setAttribute("data-global-segment-analytics-key", i);
124+
t.src =
125+
"https://cdn.segment.com/analytics.js/v1/" +
126+
key +
127+
"/analytics.min.js";
128+
r.parentNode.insertBefore(t, r);
129+
analytics._loadOptions = n;
130+
};
131+
132+
analytics.loadWithSignals = function (key, n) {
133+
var signalsScript = document.createElement("script");
134+
signalsScript.type = "text/javascript";
135+
signalsScript.src =
136+
"https://cdn.jsdelivr.net/npm/@segment/analytics-signals@latest/dist/umd/analytics-signals.umd.js";
137+
signalsScript.async = !0;
138+
r.parentNode.insertBefore(signalsScript, r);
139+
signalsScript.onload = function () {
140+
var signalsPlugin = new SignalsPlugin();
141+
analytics.register(signalsPlugin);
142+
analytics.load(key, n)
143+
};
144+
};
145+
146+
analytics.loadWithSignals(analytics._writeKey)
147+
analytics.page()
148+
}
149+
})();
150+
</script>
151+
</head>
152+
```
29153

30-
Follow these steps to integrate the Signals SDK into your website:
154+
Verify that you only have **one snippet** in your site, then move to [Step 3: Verify and deploy events](#step-3-verify-and-deploy-events).
31155

32-
1. Add the Signals SDK to your project:
156+
### Option B: Install with a package manager
33157

34-
```bash
35-
# npm
36-
npm install @segment/analytics-signals
37-
# yarn
38-
yarn add @segment/analytics-signals
39-
# pnpm
40-
pnpm install @segment/analytics-signals
41-
```
158+
1. Add the Signals SDK to your project:
159+
```bash
160+
# npm
161+
npm install @segment/analytics-signals
162+
# yarn
163+
yarn add @segment/analytics-signals
164+
# pnpm
165+
pnpm install @segment/analytics-signals
166+
```
42167

43168
2. Add the initialization code and configuration options:
44169

45-
> success ""
46-
> see [configuration options](#configuration-options) for a complete list.
170+
> success ""
171+
> see [configuration options](#configuration-options) for a complete list.
47172
48-
```ts
49-
// analytics.js/ts
50-
import { AnalyticsBrowser } from '@segment/analytics-next'
51-
import { SignalsPlugin } from '@segment/analytics-signals'
173+
```ts
174+
// analytics.js/ts
175+
import { AnalyticsBrowser } from "@segment/analytics-next";
176+
import { SignalsPlugin } from "@segment/analytics-signals";
52177

53-
const analytics = new AnalyticsBrowser()
54-
const signalsPlugin = new SignalsPlugin()
55-
analytics.register(signalsPlugin)
178+
export const analytics = new AnalyticsBrowser();
56179

57-
analytics.load({
58-
writeKey: '<YOUR_WRITE_KEY>'
59-
})
60-
```
180+
const signalsPlugin = new SignalsPlugin();
181+
182+
analytics.register(signalsPlugin);
61183

62-
Verify that you replaced `<WRITE_KEY>` with the actual write key you copied in Step 1.
184+
analytics.load({
185+
writeKey: "<YOUR_WRITE_KEY>",
186+
});
187+
```
63188

64-
4. Build and run your app.
189+
Verify that you replaced `<YOUR_WRITE_KEY>` with the actual write key you copied in Step 1.
190+
191+
3. Build and run your app.
65192

66193
## Step 3: Verify and deploy events
67194

@@ -71,70 +198,129 @@ After integrating the SDK and running your app, verify that Segment is collectin
71198
2. In the source overview, look for the **Event Builder** tab. If the tab doesn’t appear:
72199
- Make sure you've installed the SDK correctly.
73200
- Reach out to your Segment CSM to confirm that your workspace has the necessary feature flags enabled.
74-
![The Event Builder tab shown in the navigation bar between Debugger and Schema in a Segment Source](images/event_builder_tab.png)
75-
3. Open the **Event Builder** and follow the on-screen instructions to start signal detection.
201+
![The Event Builder tab shown in the navigation bar between Debugger and Schema in a Segment Source](images/event_builder_tab.png)
202+
203+
3. Open the **Event Builder** and follow the on-screen instructions to start signal detection.
76204
- To collect signals in the UI, visit your site in a browser using the query string:`?segment_signals_debug=true`
77205
4. Interact with your app to trigger signals: click buttons, navigate pages, submit forms, and so on. Segment collects and displays these as signals in real time.
78206
5. From the signals list, click **Configure event** to define a new event based on one or more signals. After configuring the event, click **Publish event rules**.
79207

80-
81208
### Debugging
209+
82210
#### Enable debug mode
211+
83212
Values sent to the signals API are redacted by default.
84-
This adds a local storage key. To disable redaction, add a magic query string:
213+
This adds a local storage key. To disable redaction, add a magic query string:
214+
85215
```
86216
https://my-website.com?segment_signals_debug=true
87217
```
88-
You can *turn off debugging* by doing:
218+
219+
You can _turn off debugging_ by doing:
220+
89221
```
90222
https://my-website.com?segment_signals_debug=false
91223
```
92224

93225
### Advanced
94226

95-
#### Emitting custom signals
227+
#### Emitting custom signals
228+
96229
If you need to listen for data that is unavailable to the Signals plugin by default, you can create and emit a custom signal:
97230

98231
```ts
99-
import { signalsPlugin } from './analytics' // assuming you exported your plugin instance.
232+
var signalsPlugin = new SignalsPlugin(); // or use the global variable if you registered it globally
233+
signalsPlugin.addSignal({ someData: 'foo' })
100234

101-
signalsPlugin.addSignal({
102-
type: 'userDefined',
103-
data: { foo: 'bar' }
104-
})
235+
236+
// emits a signal with the following shape
237+
{
238+
type: 'userDefined'
239+
data: { someData: 'foo', ... }
240+
}
105241
```
106242

107243
#### Listening to signals
244+
108245
```ts
109-
const signalsPlugin = new SignalsPlugin()
110-
signalsPlugin.onSignal((signal) => console.log(signal))
246+
const signalsPlugin = new SignalsPlugin();
247+
signalsPlugin.onSignal((signal) => console.log(signal));
111248
```
112249

113-
### Emitting Signals
250+
#### Middleware / Plugins
251+
252+
You can drop or modify signals using middleware:
253+
114254
```ts
115-
const signalsPlugin = new SignalsPlugin()
116-
signalsPlugin.addSignal({
117-
type: 'userDefined',
118-
data: { foo: 'bar' }
119-
})
255+
import { SignalsPlugin, SignalsMiddleware } from "@segment/analytics-signals";
256+
257+
class MyMiddleware implements SignalsMiddleware {
258+
process(signal: Signal) {
259+
// drop all instrumentation signals
260+
if (signal.type === "instrumentation") {
261+
return null;
262+
} else {
263+
return signal;
264+
}
265+
}
266+
}
267+
268+
const signalsPlugin = new SignalsPlugin({
269+
middleware: [new MyMiddleware()],
270+
});
271+
analytics.register(signalsPlugin);
272+
```
273+
274+
#### Sandbox Strategies
275+
276+
If you get CSP errors, you can use the experimental 'global' sandbox strategy:
277+
278+
```ts
279+
new SignalsPlugin({ sandboxStrategy: "global" });
120280
```
121281

122282
## Configuration Options
123283

124-
Using the Signals Configuration object, you can control the destination, frequency, and types of signals that Segment automatically tracks within your application. The following table details the configuration options for Signals-Kotlin.
284+
Using the Signals Configuration object, you can control the destination, frequency, and types of signals that Segment automatically tracks within your application. The following table details the configuration options for Signals Web.
285+
286+
| `Option` | Required | Value | Description |
287+
| ------------------------ | -------- | -------------------- | ------------------------------------------------------------------------------------------------------------------ |
288+
| `maxBufferSize` | No | number | The number of signals to be kept for JavaScript inspection. This buffer is first-in, first-out. Default is `1000`. |
289+
| `enableDebugLogging` | No | boolean | Enable debug logs. |
290+
| `disableSignalRedaction` | No | boolean | Disable default Signal data redaction. |
291+
| `apiHost` | No | string | Override the default signals API host. Default is `signals.segment.io/v1`. |
292+
| `functionHost` | No | string | Override the default edge host. Default is `cdn.edgefn.segment.com` |
293+
| `flushAt` | No | number | How many signals to flush at once when sending to the signals API. Default is `5` . |
294+
| `flushInterval` | No | number | How many ms to wait before flushing signals to the API. The default is `2000`. |
295+
| `middleware` | No | SignalsMiddleware[] | Array of middleware to process signals before they are sent. |
296+
| `sandboxStrategy` | No | 'global' \| 'iframe' | Sandbox strategy for signal collection. Use 'global' if getting CSP errors. Default is 'iframe'. |
297+
298+
## Core Signal Types
299+
300+
Auto-Instrumentation collects different types of signals automatically:
301+
302+
### `interaction`
303+
304+
Interaction signals emit in response to a user interaction (like clicks or form submissions)
305+
306+
### `instrumentation`
307+
308+
Instrumentation signals emit whenever a Segment event is emitted.
309+
310+
### `navigation`
311+
312+
Navigation signals emit whenever the URL changes.
313+
314+
> Note: you can also rely on the initial analytics.page() call, which you can access as an Instrumentation signal.
315+
316+
### `network`
317+
318+
Network signals emit when an HTTP Request is made, or an HTTP Response is received. To emit a network signal, the network activity must have the following requirements:
125319

126-
| `Option` | Required | Value | Description |
127-
| ------------------- | -------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
128-
| `writeKey` | Yes | string | Source write key |
129-
| `maxBufferSize` | No | number | The number of signals to be kept for JavaScript inspection. This buffer is first-in, first-out. Default is `1000`. |
130-
| `processSignal` | No | string | Override the default signal processing function from the edge function. If this is set, the edge function will not be used.
131-
| `enableDebugLogging` | No | boolean | Enable debug logs.
132-
| `disableSignalRedaction` | No | boolean | Disable default Signal data redaction.
133-
| `apiHost` | No | string | Override the default signals API host. Default is `signals.segment.io/v1`.
134-
| `functionHost` | No | string | Override the default edge host. Default is `cdn.edgefn.segment.com`
135-
| `flushAt` | No | number | How many signals to flush at once when sending to the signals API. Default is `5` . |
136-
| `flushInterval` | No | number | How many ms to wait before flushing signals to the API. The default is `2000`. |
320+
- Initiated using the `fetch` API
321+
- First party domain (for example, if on `foo.com`, then `foo.com/api/products`, but not `bar.com/api/products`)
322+
- Contains the content-type: `application/json`
137323

138324
## Next steps
139325

140-
This guide walked you through initial Signals SDK/Auto-Instrumentation setup. Next, read the [Auto-Instrumentation Signals Implementation Guide](/docs/connections/auto-instrumentation/configuration/), which dives deeper into Signals and offers example rules.
326+
This guide walked you through initial Signals SDK/Auto-Instrumentation setup. Next, read the [Auto-Instrumentation Signals Implementation Guide](/docs/connections/auto-instrumentation/configuration/), which dives deeper into Signals and offers example rules.

0 commit comments

Comments
 (0)