Skip to content

Commit 3c0e175

Browse files
Lms24coolguyzone
andauthored
feat(js): Update web worker guide with new webWorkerIntegration APIs (#14395)
<!-- Use this checklist to make sure your PR is ready for merge. You may delete any sections you don't need. --> ## DESCRIBE YOUR PR closes getsentry/sentry-javascript#16977 closes getsentry/sentry-javascript#16974 This PR adds documentation for two new `WebWorker`-related APIs: - `Sentry.webWorkerIntegration()` - `Sentry.registerWebWorker()` More details in getsentry/sentry-javascript#16981 I also gave the entire web worker guide a facelift, removed some unnecessary `notSupported` platforms and added an integration page for the new integration. Also, the guide now includes a paragraph about configuring Vite correctly for worker builds which was raised in getsentry/sentry-javascript-bundler-plugins#755. ## IS YOUR CHANGE URGENT? Help us prioritize incoming PRs by letting us know when the change needs to go live. - [ ] Urgent deadline (GA date, etc.): <!-- ENTER DATE HERE --> - [ ] Other deadline: <!-- ENTER DATE HERE --> - [x] None: Not urgent, can wait up to 1 week+ (only to be merged after 9.40.0 was released) ## SLA - Teamwork makes the dream work, so please add a reviewer to your PRs. - Please give the docs team up to 1 week to review your PR unless you've added an urgent due date to it. Thanks in advance for your help! ## PRE-MERGE CHECKLIST *Make sure you've checked the following before merging your changes:* - [x] Checked Vercel preview for correctness, including links - [x] PR was reviewed and approved by any necessary SMEs (subject matter experts) - [ ] PR was reviewed and approved by a member of the [Sentry docs team](https://github.com/orgs/getsentry/teams/docs) ## LEGAL BOILERPLATE <!-- Sentry employees and contractors can delete or ignore this section. --> Look, I get it. The entity doing business as "Sentry" was incorporated in the State of Delaware in 2015 as Functional Software, Inc. and is gonna need some rights from me in order to utilize my contributions in this here PR. So here's the deal: I retain all rights, title and interest in and to my contributions, and by keeping this boilerplate intact I confirm that Sentry can use, modify, copy, and redistribute my contributions, under Sentry's choice of terms. ## EXTRA RESOURCES - [Sentry Docs contributor guide](https://docs.sentry.io/contributing/) --------- Co-authored-by: Alex Krawiec <[email protected]>
1 parent d8c6fad commit 3c0e175

File tree

3 files changed

+165
-44
lines changed

3 files changed

+165
-44
lines changed

docs/platforms/javascript/common/best-practices/web-workers.mdx

Lines changed: 112 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,7 @@ sidebar_order: 9000
66
supported:
77
- javascript
88
notSupported:
9-
- javascript.angular
109
- javascript.cordova
11-
- javascript.electron
12-
- javascript.ember
13-
- javascript.gatsby
14-
- javascript.nextjs
15-
- javascript.nuxt
16-
- javascript.react
17-
- javascript.solid
18-
- javascript.solidstart
19-
- javascript.vue
20-
- javascript.wasm
2110
- javascript.node
2211
- javascript.aws-lambda
2312
- javascript.azure-functions
@@ -29,28 +18,22 @@ notSupported:
2918
- javascript.hono
3019
- javascript.koa
3120
- javascript.nestjs
32-
- javascript.tanstackstart-react
21+
- javascript.deno
22+
- javascript.cloudflare
23+
- javascript.bun
3324
---
3425

35-
Sentry's Browser SDK supports [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). To capture unhandled errors from Web Workers:
26+
Sentry's Browser SDK supports the [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
27+
You can use the SDK in different ways, though we recommend initializing it in the main thread to capture unhandled errors from workers automatically.
3628

37-
Install `@sentry/browser` using your package manager:
29+
## Recommended Setup
3830

39-
```bash {tabTitle:npm}
40-
npm install @sentry/browser --save
41-
```
42-
43-
```bash {tabTitle:yarn}
44-
yarn add @sentry/browser
45-
```
31+
_Available since_ : 9.40.0
4632

47-
```bash {tabTitle:pnpm}
48-
pnpm add @sentry/browser
49-
```
50-
51-
Then you can use it:
33+
To capture unhandled errors from Web Workers, initialize Sentry in your application code that runs on the main thread
34+
and let the SDK know about the web worker:
5235

53-
```javascript {filename:index.js}
36+
```javascript {filename:index.js} {1-5,9-10}
5437
import * as Sentry from "@sentry/browser";
5538

5639
Sentry.init({
@@ -59,34 +42,75 @@ Sentry.init({
5942

6043
const worker = new Worker("worker.js");
6144

45+
// Add the integration before listening to worker messages
46+
Sentry.addIntegration(Sentry.webWorkerIntegration({ worker }));
47+
48+
worker.onmessage = (event) => {
49+
// ...
50+
}
51+
```
52+
53+
Then, establish communication between the worker and the SDK:
54+
55+
```javascript {filename:worker.js}{1-4}
56+
import * as Sentry from "@sentry/browser";
57+
58+
// Call this before posting any message
59+
Sentry.registerWorker({ self })
60+
6261
// Errors from `onmessage` callback of `worker.js`
63-
// will be captured.
64-
worker.postMessage("Hello!");
62+
// will be captured automatically.
63+
self.postMessage("Worker ready!");
64+
self.onmessage = (event) => {
65+
// ...
66+
}
6567
```
6668

67-
<Alert level="warning" title="Manual Capturing">
69+
<Alert level="warning" title="The Order Matters">
6870

69-
To capture errors or messages manually, such as to use `captureMessage` or `captureException` inside Web Workers, Sentry should be initialized inside each Web Workers' own scope. Only unhandled errors will be captured and sent to Sentry without worker-level initialization.
71+
Make sure to initialize Sentry in both the main thread and the worker before either starts listening for messages.
72+
The Sentry SDK sends messages from the worker to the main thread, so if you start listening before Sentry is initialized,
73+
the messages will appear in your listeners and you will have to handle them manually.
7074

7175
</Alert>
7276

73-
#### Usage Without Worker-Level Initialization
77+
### Multiple Workers
78+
79+
The `sentryWebWorkerIntegration` allows you to register multiple workers.
80+
You can add them either when you initialize the integration, or later on.
81+
This is helpful, if you have workers that are initialized at different points in time in your application lifecycle.
7482

75-
```javascript {filename:worker.js}
83+
```javascript {filename:index.js} {1-5, 10-14, 18}
7684
import * as Sentry from "@sentry/browser";
7785

78-
self.onmessage = (message) => {
79-
// This will fail silently.
80-
Sentry.captureMessage("Message received");
86+
Sentry.init({
87+
dsn: "___PUBLIC_DSN___",
88+
});
8189

82-
// This error will be captured.
83-
throw new Error();
84-
};
90+
const worker1 = new Worker("worker.js");
91+
const worker2 = new Worker("worker2.js");
92+
93+
// Multiple workers can be added directly:
94+
const webWorkerIntegration = Sentry.webWorkerIntegration({ worker: [worker1, worker2] });
95+
Sentry.addIntegration(webWorkerIntegration);
96+
97+
// or later on:
98+
const worker3 = new Worker("worker3.js");
99+
webWorkerIntegration.addWorker(worker3);
85100
```
86101

87-
#### Usage With Worker-Level Initialization
102+
<Alert level="warning" title="Keep in Mind">
103+
104+
- Every worker must call `Sentry.registerWorker({ self })` to register itself with the SDK.
105+
- Do not call `Sentry.webWorkerIntegration()` multiple times! This will lead to unexpected behavior.
106+
107+
</Alert>
108+
109+
## Manually Capturing Errors
88110

89-
```javascript {filename:worker.js}
111+
To capture errors or messages manually, via `Sentry.captureMessage` or `Sentry.captureException` inside Web Workers, you can also import the SDK in the worker and initialize it.
112+
113+
```javascript {filename:worker.js} {1-5,9}
90114
import * as Sentry from "@sentry/browser";
91115

92116
Sentry.init({
@@ -102,10 +126,54 @@ self.onmessage = (message) => {
102126
};
103127
```
104128

129+
Note that initializing the SDK in the worker **completely decouples** it from the SDK running on the main thread.
130+
This means that data like user, tags, traces or scope data set on either side will not be shared with the other side.
131+
132+
Sometimes, this is the better approach, for instance if you develop a worker that is used in arbitrary applications.
133+
Other times, if the worker is just part of your application, you likely want to use the [SDK from the main thread](#recommended-setup).
134+
135+
<Alert level="warning" title="Keep in Mind">
136+
137+
If you initialize the SDK in the worker, don't use the `Sentry.webWorkerIntegration` to register the worker.
138+
Likewise, don't use the `Sentry.registerWorker` in the worker. Both methods are only supposed to be used when relying on the SDK [from the main thread](#recommended-setup).
139+
140+
</Alert>
141+
105142
### Integrations
106143

107-
Note, that if you use non-default integrations inside web workers, they may not function as expected. But non-default integrations that are enabled outside of a worker’s scope won’t be affected and will function as expected. This includes Session Replay.
144+
Note, that if you use non-default integrations inside web workers, they may not function as expected.
145+
However, non-default integrations that are enabled on the main thread SDK won't be affected and will work as expected.
146+
This includes Session Replay.
147+
148+
## Source Maps
149+
150+
To ensure that errors from web workers are properly mapped to their original source code, you need to provide source maps to Sentry.
151+
You likely already provide source maps to Sentry for your main application code, but you might need to make adjustments for your worker.
152+
153+
Importantly, ensure that your bundler also **emits source maps** for the worker bundle(s).
108154

109-
### Source Maps
155+
### Vite
156+
If you use Vite to build your worker, note that the worker build does not take the same plugin as the main code build.
157+
Therefore, you need to add Sentry's Vite plugin to the worker build, in addition to the top-level `plugins` array:
110158

111-
Sentry's source maps integration is supported inside Web Workers, if provided. Learn more about providing your [source maps](/platforms/javascript/sourcemaps/) to Sentry.
159+
```javascript {filename:vite.config.mjs}{1-4,8-9,13,16-17}
160+
const sentryPlugin = sentryVitePlugin({
161+
org: "sentry-sdks",
162+
project: "javascript",
163+
});
164+
165+
export default defineConfig({
166+
build: {
167+
// This enables source maps for main and worker bundles
168+
sourcemap: "hidden",
169+
},
170+
171+
// Vite plugin for main bundle
172+
plugins: [sentryPlugin],
173+
174+
worker: {
175+
// Vite plugin for worker bundle
176+
plugins: () => [...sentryPlugin],
177+
},
178+
});
179+
```
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
title: WebWorker
3+
description: "Connect Web Workers with the SDK running on the main thread"
4+
notSupported:
5+
- javascript.cordova
6+
- javascript.node
7+
- javascript.aws-lambda
8+
- javascript.azure-functions
9+
- javascript.connect
10+
- javascript.express
11+
- javascript.fastify
12+
- javascript.gcp-functions
13+
- javascript.hapi
14+
- javascript.hono
15+
- javascript.koa
16+
- javascript.nestjs
17+
- javascript.deno
18+
- javascript.cloudflare
19+
- javascript.bun
20+
---
21+
22+
_Import name: `Sentry.webWorkerIntegration`_
23+
24+
This integration, together with `Sentry.registerWorker()`, establishes communication between the browser's main thread and one or more [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
25+
It listens to worker messages from the passed workers and forwards them to the main thread.
26+
27+
Read our <PlatformLink to="/best-practices/web-workers/">Web Worker Guide</PlatformLink> for more information.
28+
29+
<Expandable title="What does this integration do?">
30+
31+
This integration listens to a message sent from the worker when it calls `Sentry.registerWorker({ self })`.
32+
The purpose is to sync source map information (debugIds) between the main thread and the worker so that worker
33+
errors caught by the main thread SDK are properly mapped to the worker's source code.
34+
35+
</Expandable>
36+
37+
38+
## Options
39+
40+
### `worker`
41+
42+
_Type: `Worker | Array<Worker>`_
43+
44+
The web worker(s) to listen to. Every worker must call `Sentry.registerWorker({ self })` to register itself with the SDK.
45+
46+
## Methods
47+
48+
### `addWorker(worker: Worker)`
49+
50+
Adds a worker to the integration, after the integraion was already initialized and added to the SDK.
51+
This is useful if you have workers that are initialized at later point in your application's lifecycle.
52+
Note that every worker must call `Sentry.registerWorker({ self })` to register itself with the SDK.

platform-includes/configuration/integrations/javascript.mdx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@
2929
| [`statsigIntegration`](./statsig) | | | | ||
3030
| [`supabaseIntegration`](./supabase) | ||| | |
3131
| [`unleashIntegration`](./unleash) | | | | ||
32+
| [`webWorkerIntegration`](./webworker) | || | | |

0 commit comments

Comments
 (0)