# In-app analytics and error monitoring

Send usage events and errors from your UI extension to a third-party service.

[App analytics](https://docs.stripe.com/stripe-apps/analytics.md) shows how many users install your app and view its listing. To understand how users interact with your app after installing it, send events from your UI extension to your own analytics or error-monitoring service.

## Before you begin

- [Create an app](https://docs.stripe.com/stripe-apps/create-app.md) with a `stripe.dashboard.fullpage` view that uses [routing](https://docs.stripe.com/stripe-apps/routing.md), and an [onboarding view](https://docs.stripe.com/stripe-apps/onboarding.md).
- Create a Sentry project with [Logs](https://docs.sentry.io/product/logs/) enabled, and copy its DSN.
- Install the Sentry SDK with your app’s package manager, for example `pnpm add @sentry/react`. If your app uses a [v2 manifest](https://docs.stripe.com/stripe-apps/reference/app-manifest.md?manifestVersion=manifest-v2) and has a `ui` directory, run the command there.

## Allow the service in your app manifest

This guide uses [Sentry](https://sentry.io) as the example. Replace `track()`, `initSentry()`, and the other `Sentry.*` calls with your service’s equivalents to use a different service.

UI extensions can only send requests to URLs listed in the `connect-src` of your app manifest. Run `stripe apps grant url` with your service’s ingest URL and a purpose:

```bash
stripe apps grant url "https://o<ORG_ID>.ingest.us.sentry.io/api/" "Send anonymous usage events and error reports to Sentry"
```

The command adds the URL to your app manifest:

```json
"content_security_policy": {
  "connect-src": ["https://o<ORG_ID>.ingest.us.sentry.io/api/"],
  "purpose": "Send anonymous usage events and error reports to Sentry"
}
```

Replace the host with the one in your DSN. Each `connect-src` URL must:

- Use HTTPS.
- Contain a path. End the path with a trailing slash to allow all paths under it.

For more details, see [Use third-party APIs](https://docs.stripe.com/stripe-apps/build-ui.md#use-third-party-apis).

## Initialize Sentry

Create a helper that initializes Sentry once, so each of your views can call it. Pass the view’s context to attach the account to errors and logs:

```ts
import * as Sentry from '@sentry/react';
import type {ExtensionContextValue} from '@stripe/ui-extension-sdk/context';

const SENTRY_DSN = 'https://<KEY>@o<ORG_ID>.ingest.us.sentry.io/<PROJECT_ID>';

let initialized = false;

export function initSentry({userContext}: ExtensionContextValue) {
  if (initialized) return;
  Sentry.init({dsn: SENTRY_DSN, enableLogs: true});
  initialized = true;
  Sentry.setUser({id: userContext?.account.id});
}
```

Call `initSentry(context)` at the top of each view component, instead of in a `useEffect`, so events sent when the view first renders are captured. Views in the same frame, such as your drawer views, share one Sentry client, so calling `initSentry` more than once has no effect past the first call.

## Create a tracking helper

Send all usage events through one helper so you can change services in one place. This example sends each event to Sentry Logs:

```ts
import * as Sentry from '@sentry/react';

export function track(name: string, props: Record<string, unknown> = {}) {
  Sentry.logger.info(name, props);
}
```

## Track onboarding progress 

Send an event each time a user reaches a step of your [OnboardingView](https://docs.stripe.com/stripe-apps/components/onboardingview.md). A user’s last `onboarding.step_viewed` event without a later `onboarding.completed` event shows where they dropped off.

```tsx
import {useEffect, useState} from 'react';
import {Button, OnboardingView} from '@stripe/ui-extension-sdk/ui';
import type {ExtensionContextValue} from '@stripe/ui-extension-sdk/context';
import {track} from '../analytics';
import {initSentry} from '../sentry';

const STEPS = ['Connect your account', 'Configure settings', 'Review'];

export default function Onboarding(context: ExtensionContextValue) {
  initSentry(context);
  const viewport = context.environment?.viewportID;

  const [step, setStep] = useState(0);
  const completed = step >= STEPS.length;

  useEffect(() => {
    track(completed ? 'onboarding.completed' : 'onboarding.step_viewed', {step, viewport});
  }, [step, completed, viewport]);

  return (
    <OnboardingView
      title={STEPS[step] ?? 'All set'}
      completed={completed}
      tasks={STEPS.map((title, i) => ({
        title,
        status: i < step ? 'complete' : i === step ? 'in-progress' : 'not-started',
      }))}
    >
      <Button type="primary" onPress={() => setStep(step + 1)}>
        Continue
      </Button>
    </OnboardingView>
  );
}
```

## Track route transitions 

Use [useAppRoute](https://docs.stripe.com/stripe-apps/routing.md#read-the-current-route) to send an event when the full-page route changes.

```ts
import {useEffect} from 'react';
import {useAppRoute} from '@stripe/ui-extension-sdk/navigation';
import {track} from './analytics';

export function useRouteTracking() {
  const route = useAppRoute();
  const routeParamsKey = JSON.stringify(route.routeParams);

  useEffect(() => {
    track('route.viewed', {route: route.key, ...route.routeParams});
  }, [route.key, routeParamsKey]);
}
```

`useAppRoute` only works inside [AppRouter](https://docs.stripe.com/stripe-apps/routing.md#wire-up-the-approuter), so call `useRouteTracking()` from the components your routes render.

## Capture errors 

`Sentry.init` captures uncaught errors and unhandled promise rejections. Wrap `AppRouter` in `Sentry.ErrorBoundary` to also report render errors and show a fallback, and use `beforeCapture` to tag the error with the viewport that raised it. Put the boundary inside `FullPageView`, so `FullPageView` stays the root component:

```tsx
import {useEffect} from 'react';
import * as Sentry from '@sentry/react';
import {Banner, FullPageView} from '@stripe/ui-extension-sdk/ui';
import {AppRouter, NavigationProvider} from '@stripe/ui-extension-sdk/navigation';
import type {ExtensionContextValue} from '@stripe/ui-extension-sdk/context';
import {routes} from '../routes';
import {installCspMonitor} from '../analytics';
import {initSentry} from '../sentry';

export default function FullPage(context: ExtensionContextValue) {
  initSentry(context);
  useEffect(installCspMonitor, []);

  return (
    <NavigationProvider routes={routes}>
      <FullPageView>
        <Sentry.ErrorBoundary
          beforeCapture={(scope) => scope.setTag('viewport', context.environment?.viewportID)}
          fallback={<Banner type="critical" title="Something went wrong" />}
        >
          <AppRouter context={context} redirectOnNotFound={{key: 'home'}} />
        </Sentry.ErrorBoundary>
      </FullPageView>
    </NavigationProvider>
  );
}
```

`installCspMonitor` is defined in [Detect blocked requests](https://docs.stripe.com/stripe-apps/in-app-analytics.md#blocked-requests).

Do the same in your onboarding view: import `Sentry` and `Banner` in `Onboarding.tsx`, then wrap the children of `OnboardingView`:

```tsx
<OnboardingView /* ...props */>
  <Sentry.ErrorBoundary
    beforeCapture={(scope) => scope.setTag('viewport', viewport)}
    fallback={<Banner type="critical" title="Something went wrong" />}
  >
    <Button type="primary" onPress={() => setStep(step + 1)}>
      Continue
    </Button>
  </Sentry.ErrorBoundary>
</OnboardingView>
```

## Detect blocked requests 

The browser fires a [securitypolicyviolation](https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent) event when a request’s URL isn’t in your `connect-src`. Add a listener to `analytics.ts`:

```ts
let installed = false;

export function installCspMonitor() {
  if (installed) return;
  installed = true;
  document.addEventListener('securitypolicyviolation', (e) => {
    const host = e.blockedURI.startsWith('http')
      ? new URL(e.blockedURI).host
      : e.blockedURI;
    Sentry.captureMessage(`CSP: ${e.effectiveDirective} blocked ${host}`, {
      level: 'warning',
      fingerprint: ['csp', e.effectiveDirective, host],
      extra: {blockedURI: e.blockedURI},
    });
  });
}
```

Call `installCspMonitor` once from your full-page view, as shown in [Capture errors](https://docs.stripe.com/stripe-apps/in-app-analytics.md#errors).

Each violation is reported as an issue grouped by directive and blocked host. `blockedURI` is a keyword instead of a URL for violations that aren’t requests, such as a dependency that calls `eval`.

## Limitations 

- **Best-effort unmount cleanup**: The Dashboard can terminate your app without running effect cleanups, so don’t rely on unmount to send a final event. Infer drop-off from the last event a user sent.
- **Blocked images aren’t reported**: An [Img](https://docs.stripe.com/stripe-apps/components/img.md) whose URL isn’t in your `image-src` doesn’t fire a `securitypolicyviolation` event, so `installCspMonitor` doesn’t report it.
- **Session-only storage**: `localStorage` isn’t available to your app. Use the [useStorage](https://docs.stripe.com/stripe-apps/reference/extensions-sdk-api.md#useStorage) hook to share onboarding progress between your app’s views. Its values don’t persist between sessions, so store progress in [your back end](https://docs.stripe.com/stripe-apps/build-backend.md#authenticate-ui-to-backend) to resume onboarding where a user left off.

## See also

- [App analytics](https://docs.stripe.com/stripe-apps/analytics.md)
- [Routing](https://docs.stripe.com/stripe-apps/routing.md)
- [Onboarding](https://docs.stripe.com/stripe-apps/onboarding.md)
