Skip to content

feat(javascript): More micro frontends features #7558

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 9 commits into from
Aug 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 161 additions & 44 deletions src/platforms/javascript/common/configuration/micro-frontend-support.mdx
Original file line number Diff line number Diff line change
@@ -1,15 +1,97 @@
---
title: Micro Frontend Support
sidebar_order: 200
description: ""
keywords: ["micro frontend", "multiplexed transport"]
keywords:
[
"micro frontend",
"multiplexed transport",
"module federation",
"module metadata",
]
---

The recommended way to use the Sentry SDK with Micro Frontend is to set up a multiplexed transport when calling `Sentry.init`. The multiplexed transport will send events to different Sentry projects based on the attributes on that event, which is how you can isolate events from a specific micro-frontend to a specific Sentry project.
If your frontend includes JavaScript bundles from multiple sources with
different release cycles, you may want to identify these or route events to specific projects. This is especially useful if you've set up [module federation](https://module-federation.github.io/) or a similar frontend architecture.

## Identifying the source of errors

To identify the source of an error, you must inject metadata that helps identify which bundles were responsible for an error. You can do this with the `@sentry/webpack-plugin` by enabling the `_experiments.moduleMetadata` option.

Requires version `2.5.0` or higher of `@sentry/webpack-plugin`.

`moduleMetadata` can be any serializable data or alternatively a function that
returns serializable data. If you supply a function, it will be passed an object
containing the `org`, `project`, and `release` strings.

```javascript
// webpack.config.js
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

module.exports = {
devtool: "source-map",
plugins: [
sentryWebpackPlugin({
/* Other plugin config */
_experiments: {
moduleMetadata: ({ org, project, release }) => {
return { team: 'frontend', release },
}
},
}),
],
};
```

### `ModuleMetadata` Integration

Requires SDK version `7.59.0` or higher.

Once metadata has been injected into modules, the `ModuleMetadata` integration
can be used to look up that metadata and attach it to stack frames with
matching file names. This metadata is then available in other integrations or in
the `beforeSend` callback as the `module_metadata` property on each
`StackFrame`. This can be used to identify which bundles may be responsible
for an error and used to tag or route events.

```javascript
import * as Sentry from "@sentry/browser";
import { ModuleMetadata } from "@sentry/core";

Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [ new ModuleMetadata() ]
beforeSend: (event) => {
const frames = event?.exception?.values?.[0].stacktrace.frames || [];
// Get all team names in the stack frames
const teams = frames.filter(frame => frame.module_metadata && frame.module_metadata.team)
.map(frame => frame.module_metadata.team);
// If there are teams, add them as extra data to the event
if(teams.length > 0){
event.extra = {
...event.extra,
teams
};
}

return event;
},
});

Sentry.captureException(new Error("oh no!"));
```

## Routing events to different projects

Once you've identified which module or modules are likely to be responsible for
an error, you may want to send these events to different Sentry projects. The
multiplexed transport can route events to different Sentry projects based on the
attributes on an event.

Requires SDK version `7.50.0` or higher.

The example below uses the `feature` tag to determine which Sentry project to send the event to by using different DSNs. If the event does not have a `feature` tag, we send it to the fallback DSN defined in `Sentry.init`.
The example below uses a `feature` tag to determine which Sentry project to
send the event to. If the event does not have a `feature` tag, we send it to the
fallback DSN defined in `Sentry.init`.

```typescript
import { captureException, init, makeFetchTransport } from "@sentry/browser";
Expand All @@ -19,9 +101,9 @@ function dsnFromFeature({ getEvent }) {
const event = getEvent();
switch (event?.tags?.feature) {
case "cart":
return ["__CART_DSN__"];
return [{ dsn: "__CART_DSN__", release: "[email protected]" }];
case "gallery":
return ["__GALLERY_DSN__"];
return [{ dsn: "__GALLERY_DSN__", release: "[email protected]" }];
default:
}
return [];
Expand All @@ -40,15 +122,11 @@ captureException(new Error("oh no!"), (scope) => {

You can then set tags/contexts on events in individual micro-frontends to decide which Sentry project to send the event to.

<Alert level="warning" title="Note">

Currently, there is no way to isolate tags/contexts/breadcrumbs/spans to events sent to a specific Sentry project. This is because browsers do not have support for async contexts, which is required for this functionality to work. Once the [tc39 Async Context](https://github.com/tc39/proposal-async-context) proposal is implemented in all browsers, we will be able to add this functionality.

</Alert>

## `makeMultiplexedTransport` API
### `makeMultiplexedTransport` API

`makeMultiplexedTransport` takes an instance of a transport (we recommend `makeFetchTransport`) and a matcher function that returns an array of DSNs.
`makeMultiplexedTransport` takes an instance of a transport (we recommend
`makeFetchTransport`) and a matcher function that returns an array of objects
containing the DSN and optionally the release.

```typescript
type EnvelopeItemType =
Expand All @@ -69,14 +147,19 @@ interface MatchParam {
envelope: Envelope;
/**
* A function that returns an event from the envelope if one exists. You can optionally pass an array of envelope item
* types to filter by - only envelopes matching the given types will be multiplexed.
* types to filter by - only envelopes matching the given types will be returned.
*
* @param types Defaults to ['event'] (only error events will be matched)
* @param types Defaults to ['event'] (only error events will be returned)
*/
getEvent(types?: EnvelopeItemType[]): Event | undefined;
}

type Matcher = (param: MatchParam) => string[];
interface RouteTo {
dsn: string;
release?: string;
}

type Matcher = (param: MatchParam) => RouteTo[];

declare function makeMultiplexedTransport(
transport: (options: TransportOptions) => Transport,
Expand All @@ -86,43 +169,77 @@ declare function makeMultiplexedTransport(

The matcher function runs after all client processing (`beforeSend` option, event processors from integrations).

## Examples
## Combining `ModuleMetadata` and `makeMultiplexedTransport`

### Allowing Individual Micro Frontends to Add Their Own DSNs
`ModuleMetadata` and `makeMultiplexedTransport` can be used together to route
events to different Sentry projects based on the module where the error
occurred.

The example below gives a list of DSNs and tags. It uses the `tags` attribute on the event to determine which Sentry project to send the event to by using different DSNs. If the event does not have a `tags` attribute, we send it to the fallback DSN defined in `Sentry.init`. Individual micro-frontends can then mutate the `myDsns` variable to add their own DSNs and tags.

```typescript
const myDsns = [
{ dsn: "https://...", tag: "my-tag" },
{ dsn: "https://...", tag: "other-tag" },
];
Ensure your modules have injected metadata containing the project DSN and release:

function dsnFromTag({ getEvent }) {
const event = getEvent();
const opt = myDsns.find(({ tag }) => event?.tags?.includes(tag));
return opt ? [opt.dsn] : [];
}
```javascript
// webpack.config.js
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

init({
dsn: "__FALLBACK_DSN__",
transport: makeMultiplexedTransport(makeFetchTransport, dsnFromTag),
});
module.exports = {
devtool: "source-map",
plugins: [
sentryWebpackPlugin({
_experiments: {
moduleMetadata: ({ release }) => ({ dsn: "__MODULE_DSN__", release }),
},
}),
],
};
```

### Sending the Same Event to Multiple DSNs
Then when you initialize Sentry:

Since the matcher returns an array, you can enforce that an event is sent to multiple DSNs.
- Add the `ModuleMetadata` integration so metadata is attached to stack frames
- Add a `beforeSend` callback that sets an `extra` property with the target DSN/release
- Create a transport that routes events when the `extra` property is present

```typescript
```javascript
import { init, makeFetchTransport } from "@sentry/browser";
import { makeMultiplexedTransport } from "@sentry/core";

const DSN1 = "__DSN1__";
const DSN2 = "__DSN2__";
import { makeMultiplexedTransport, ModuleMetadata } from "@sentry/core";

const EXTRA_KEY = "ROUTE_TO";

const transport = makeMultiplexedTransport(makeFetchTransport, (args) => {
const event = args.getEvent();
if (
event &&
event.extra &&
EXTRA_KEY in event.extra &&
Array.isArray(event.extra[EXTRA_KEY])
) {
return event.extra[EXTRA_KEY];
}
return [];
});

init({
dsn: DSN1, // <- init dsn never gets used but need to be valid
transport: makeMultiplexedTransport(makeFetchTransport, () => [DSN1, DSN2]),
dsn: "__DEFAULT_DSN__",
integrations: [new ModuleMetadata()],
transport,
beforeSend: (event) => {
if (event?.exception?.values?.[0].stacktrace.frames) {
const frames = event.exception.values[0].stacktrace.frames;
// Find the last frame with module metadata containing a DSN
const routeTo =
frames.findLast(
(frame) => frame.module_metadata && frame.module_metadata.dsn
) || [];

if (routeTo.length) {
event.extra = {
...event.extra,
EXTRA_KEY: routeTo,
};
}
}

return event;
},
});
```