Skip to content

feat(js): Add micro-frontend docs #6754

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 4 commits into from
May 2, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
title: Micro Frontend Support
sidebar_order: 200
description: ''
keywords: ['micro frontend', 'multiplexed transport']
---

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.

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`.

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

function dsnFromFeature({ getEvent }) {
const event = getEvent();
switch(event?.tags?.feature) {
case 'cart':
return ['__CART_DSN__'];
case 'gallery':
return ['__GALLERY_DSN__'];
}
return []
}

init({
dsn: '__FALLBACK_DSN__',
transport: makeMultiplexedTransport(makeFetchTransport, dsnFromFeature)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Random question but might be relevant to document: which ones are called first: the "matcher" ("dsnFromFeature") or the init's "beforeSend"?

As an example, if I enhance my event tags at init's beforeSend (e.g. I add "event.tags.feature = cart"), will the enhanced event tags be available at this matcher (i.e. at dsnFromFeature when getEvent() is called)?

Context: before this multiplexed transport feature is available, one workaround to send different event to different Sentry project is via beforeSend and initialize a BrowserClient there (https://github.com/sentry-demos/sentry-micro-frontend/blob/5996c4b528f58696b729db9d41f4962a83c53c77/methods/simple-remote.js#LL42C28-L42C28) So when implementing this mechanism at my company, my implementation actually adds more tags there than just finding out relevant DSN to send to (e.g. I added the micro app's release info). If I could access the tags added in "beforeSend" when the matcher is called, I could reduce some code duplication. However if that's not possible, it's also ok too for me.

Thanks~

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The init's beforeSend is called before the matcher's dsnFromFeature. Will call this out in the docs - thanks for updating it!

});

captureException(new Error('oh no!', scope => {
scope.addTag('feature', 'cart');
return 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` takes an instance of a transport (we recommend `makeFetchTransport`) and a matcher function that returns an array of DSNs.

```typescript
type EnvelopeItemType =
| 'client_report'
| 'user_report'
| 'session'
| 'sessions'
| 'transaction'
| 'attachment'
| 'event'
| 'profile'
| 'replay_event'
| 'replay_recording'
| 'check_in';

interface MatchParam {
/** The envelope to be sent */
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.
*
* @param types Defaults to ['event'] (only error events will be matched)
*/
getEvent(types?: EnvelopeItemType[]): Event | undefined;
}

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

declare function makeMultiplexedTransport(
transport: (options: TransportOptions) => Transport,
matcher: Matcher
): (options: TransportOptions) => Transport;
```

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

## Examples

### Allowing Individual Micro Frontends to Add Their Own DSNs

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' },
];

function dsnFromTag({ getEvent }) {
const event = getEvent();
const opt = myDsns.find(({tag} => event?.tags?.includes(tag));
return opt ? [opt.dsn] : [];
}

init({
dsn: '__FALLBACK_DSN__',
transport: makeMultiplexedTransport(makeFetchTransport, dsnFromTag)
});
```

### Sending the Same Event to Multiple DSNs

Since the matcher returns an array, you can enforce that an event is sent to multiple DSNs.

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

const DSN1 = '__DSN1__';
const DSN2 = '__DSN2__';

init({
dsn: DSN1, // <- init dsn never gets used but need to be valid
transport: makeMultiplexedTransport(makeFetchTransport, () => [DSN1, DSN2]),
});
```