> ## Documentation Index
> Fetch the complete documentation index at: https://docs.flashcat.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced Configuration

> Configure proxying, distributed tracing, sessions, context, and manual instrumentation for the WeChat Mini Program RUM SDK

Use advanced configuration in the WeChat Mini Program RUM SDK to handle network forwarding, distributed tracing, session control, context enrichment, and manual instrumentation. You can set collection behavior during initialization and add events at runtime through the public API.

## Intake URL and Proxy

By default, the SDK sends RUM data to `https://browser.flashcat.cloud/api/v2/rum`. If your Mini Program cannot access the default URL directly, or you need to route traffic through your own gateway, use `proxy`.

### Use a String Proxy

When `proxy` is a string, the SDK removes trailing `/` characters and produces `{proxy}?ddforward={encodedPath}`. `ddforward` contains the encoded `/api/v2/rum` path and query parameters.

```javascript app.js theme={null}
flashcatRum.init({
  applicationId: "<YOUR_APPLICATION_ID>",
  clientToken: "<YOUR_CLIENT_TOKEN>",
  proxy: "https://rum-proxy.example.com/forward"
});
```

### Use a Function Proxy

When `proxy` is a function, the SDK gives you `path` and `parameters` so you can build the full URL. `path` is always `/api/v2/rum`, and `parameters` includes reporting parameters such as `ddsource`, `ddtags`, `dd-api-key`, the SDK version, and batch time.

```javascript app.js theme={null}
flashcatRum.init({
  applicationId: "<YOUR_APPLICATION_ID>",
  clientToken: "<YOUR_CLIENT_TOKEN>",
  proxy({ path, parameters }) {
    return `https://rum-proxy.example.com${path}?${parameters}`;
  }
});
```

<Info>
  When `proxy` is not configured, the SDK uses `site` to build the intake URL: `https://{site}/api/v2/rum`. The default `site` is `browser.flashcat.cloud`.
</Info>

## Distributed Tracing

The SDK can inject W3C Trace Context headers into Mini Program network requests. When enabled, sampled `wx.request`, `wx.uploadFile`, and `wx.downloadFile` calls carry a trace header, and resource events include `trace_id` and `span_id`.

```javascript app.js theme={null}
flashcatRum.init({
  applicationId: "<YOUR_APPLICATION_ID>",
  clientToken: "<YOUR_CLIENT_TOKEN>",
  tracing: {
    enabled: true,
    sampleRate: 100,
    headerName: "traceparent"
  }
});
```

| Field                      | Type    | Default       | Description                                                                                                        |
| -------------------------- | ------- | ------------- | ------------------------------------------------------------------------------------------------------------------ |
| `tracing.enabled`          | boolean | `false`       | Controls whether request trace headers are injected                                                                |
| `tracing.sampleRate`       | number  | `100`         | Request tracing sample rate, from 0 to 100. `100` means all requests are sampled, and `50` means approximately 50% |
| `tracing.headerName`       | string  | `traceparent` | Header name injected into requests                                                                                 |
| `tracing.rootTraceContext` | object  | -             | Optional root Trace Context. When configured, the SDK creates child spans from this context                        |

The default header value generated by the SDK follows the `00-{traceId}-{spanId}-{traceFlags}` format. For example:

```text theme={null}
traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
```

If `rootTraceContext` is configured, the SDK inherits the root context `traceId` and `traceFlags` and generates a new `spanId`. Otherwise, every sampled request creates a new trace context.

## Session Behavior

The SDK stores the current session through Mini Program storage and writes the session ID to every RUM event.

| Behavior                   | Value              | Description                                                            |
| -------------------------- | ------------------ | ---------------------------------------------------------------------- |
| Session expiration         | 15 minutes         | The current session expires 15 minutes after the last extension        |
| Maximum session duration   | 4 hours            | A single session does not exceed 4 hours, even if it remains active    |
| Session extension throttle | 1 minute           | The SDK extends the session expiration at most once per minute         |
| Anonymous user             | Enabled by default | The SDK generates an anonymous ID when you have not called `setUser()` |

Call `stopSession()` when the user signs out, switches accounts, or you need to split the session. After the call, the SDK clears the current session and creates a new one for the next event.

```javascript app.js theme={null}
flashcatRum.stopSession();
```

## Event Rate Limiting

The SDK rate-limits each event type per minute. The default threshold is `3000` events per event type per minute. After the threshold is reached, the SDK drops subsequent events of that type and creates a `custom` error event that describes the rate limit.

```javascript app.js theme={null}
flashcatRum.init({
  applicationId: "<YOUR_APPLICATION_ID>",
  clientToken: "<YOUR_CLIENT_TOKEN>",
  eventRateLimiterThreshold: 1000
});
```

<Tip>
  If you report many custom events in a short period, tune `eventRateLimiterThreshold` based on actual traffic to avoid dropping business events.
</Tip>

## Pre-send Processing

`beforeSend` runs before a RUM event is sent. Use it to add fields, redact context, or return `false` to drop the current event.

```javascript app.js theme={null}
flashcatRum.init({
  applicationId: "<YOUR_APPLICATION_ID>",
  clientToken: "<YOUR_CLIENT_TOKEN>",
  beforeSend(event) {
    if (event.type === "resource" && event.resource?.url?.includes("/health")) {
      return false;
    }

    event.context = {
      ...event.context,
      source: "wechat-miniprogram"
    };
  }
});
```

## User and Global Context

`setUser()` sets current user information. When `trackAnonymousUser` is enabled and the user context is empty, the SDK automatically writes the anonymous ID to `usr.id` and `usr.anonymous_id`. If you set user information, the SDK keeps your user fields and adds `usr.anonymous_id`.

```javascript app.js theme={null}
flashcatRum.setUser({
  id: "user-123",
  name: "Alice",
  role: "member"
});
```

`setGlobalContext()` sets global context. The SDK writes this object to the `context` field on subsequent events.

```javascript app.js theme={null}
flashcatRum.setGlobalContext({
  tenant: "acme",
  region: "cn"
});
```

## Manual Pages and Custom Timings

Automatic page names come from the page instance `route`. If you need to record a virtual page or use a business name for the current page, call `startPage()`.

```javascript pages/product/detail.js theme={null}
flashcatRum.startPage("product_detail");
```

`addTiming()` writes a custom timing to the current view `custom_timings`. If you pass `time`, the SDK uses the difference between that time and the current page start time. If you do not pass `time`, it uses the current time.

```javascript pages/product/detail.js theme={null}
const start = Date.now();

loadProduct().then(() => {
  flashcatRum.addTiming("product_loaded", Date.now());
});
```

Custom timing names keep only letters, numbers, `-`, `_`, `.`, `@`, and `$`. Other characters are replaced with `_`.

## Manual Actions, Errors, and Custom Events

```javascript pages/order/detail.js theme={null}
flashcatRum.addAction("submit_order", "tap");

flashcatRum.addError("payment failed", "custom");

flashcatRum.addCustomEvent("coupon_selected", {
  couponId: "coupon-123",
  discount: 20
});
```

| Method                               | Event type | Description                                                                       |
| ------------------------------------ | ---------- | --------------------------------------------------------------------------------- |
| `addAction(name, type?)`             | `action`   | Records a business action. The default `type` is `custom`                         |
| `addError(message, source?, stack?)` | `error`    | Records a business error. The public API uses `custom` when the source is omitted |
| `addCustomEvent(name, context?)`     | `custom`   | Records a custom business event with context                                      |

## Related Pages

<CardGroup cols={3}>
  <Card title="SDK Integration" icon="plug" href="/en/rum/sdk/wechat-miniprogram/sdk-integration">
    Install and initialize the WeChat Mini Program RUM SDK.
  </Card>

  <Card title="Compatibility" icon="shield-check" href="/en/rum/sdk/wechat-miniprogram/compatible">
    Learn about Mini Program base library, development tool, and platform API requirements.
  </Card>

  <Card title="Data Collection" icon="database" href="/en/rum/sdk/wechat-miniprogram/data-collection">
    Learn which page, action, request, error, and performance data the SDK collects automatically.
  </Card>
</CardGroup>
