Skip to content

Mini Program Application Integration


By integrating the SDK, you can collect performance metrics, error logs, and resource request data from WeChat Mini Program applications and report them to TrueWatch for visual analysis of application performance.

Create a Mini Program Application

  1. Go to "RUM > Application List", click "Create Application", and select "Mini Program" as the application type.
  2. In "Define Application", enter the application name and application ID, and create the application. The console generates a Client Token for this application.
  3. After the application is created, in "Select Integration Method", select Agent Auto Integration or Manual Integration, and then complete the configuration according to "Integration Configuration". For an existing Mini Program application, go to its configuration page to continue the integration.

Mini Program applications should use the Mini Program SDK described on this page. Even if they share the same business code with a Web application, you still need to integrate them separately according to the actual application type.

Select an Integration Method

Integration Method Use Cases Entry Point
Agent Auto Integration Use a coding assistant to analyze the Mini Program project and plan and complete SDK integration based on the project Copy the Agent prompt generated by the console and run it in the Mini Program code repository
Manual Integration Introduce the SDK yourself and configure reporting parameters Choose public DataWay or local environment deployment, then modify the code according to the examples on this page

Agent Auto Integration

  1. On the Mini Program application configuration page, select "Agent Auto Integration".
  2. Copy the complete prompt from "Integration Configuration", open the coding assistant in the Mini Program code repository, and paste it. The prompt should come from the current Mini Program application and use that application's ID.
  3. Complete the configuration according to the Agent integration guide, and then follow Verify Integration to confirm Mini Program data reporting and ingestion.

If the page indicates that your personal API Key or temporary authorization code is not ready, follow the prompt to generate a personal API Key, contact your administrator to grant permissions, or complete the required information, and then copy the prompt again.

Manual Integration

Usually, prefer "Use Public DataWay"; you do not need to deploy DataKit yourself. If you need to manage the data receiver yourself, or the current workspace does not provide a public DataWay address, you can choose "Local Environment Deployment".

Data Reporting Method Prerequisites Initialization Parameters
Use Public DataWay Obtain the public DataWay address and Client Token from the current application's integration configuration applicationId, site, clientToken
Local Environment Deployment Install DataKit yourself and enable the RUM Collector, and ensure that the Mini Program can access its reporting address applicationId, datakitOrigin

NPM and CDN are SDK import methods; they are independent from choosing whether to report to public DataWay or a local DataKit.

Use Public DataWay

  1. Under "Manual Integration", select "Use Public DataWay".
  2. Copy applicationId, site, and clientToken from the current application's integration configuration. Use the current site address provided by the console. Do not use the console login address or an address of another site as site.
  3. Add the domain corresponding to site to the request legal domains in the WeChat Mini Program admin console, and then complete the code configuration according to Integrate the SDK. This method does not require installing DataKit or separately configuring the RUM Collector.

Local Environment Deployment

  1. Install DataKit and enable the RUM Collector.
  2. Ensure that the network where the Mini Program is located can access the DataKit data reporting address, and as needed, install the IP geolocation database to resolve the geolocation corresponding to the user IP.
  3. Under "Manual Integration", select "Local Environment Deployment", configure datakitOrigin as the actual DataKit receiving address, and add the corresponding domain to the request legal domains in the Mini Program admin console.
  4. Initialize according to the local environment deployment example in Integrate the SDK. Do not fill in both site and clientToken.

Integrate the SDK

First choose an SDK import method, and then initialize according to the selected data reporting method. Initialize the SDK in app.js before App() is called, and initialize it only once.

Import the SDK

Prepare dependencies according to the official WeChat npm integration instructions, and then import in app.js:

const { datafluxRum } = require('@cloudcare/rum-miniapp')

Download the SDK file, place it in the Mini Program project, for example lib/dataflux-rum-miniapp.js, and then import it in app.js:

const { datafluxRum } = require('./lib/dataflux-rum-miniapp.js')

The "CDN" method in the console requires you to first download the file to the project and then import it using a local path.

Initialize the SDK

Choose only one of the following two configurations. Public DataWay uses site and clientToken, while local environment deployment uses datakitOrigin. Do not fill in both sets of reporting parameters in the same initialization configuration.

datafluxRum.init({
  applicationId: '<APPLICATION_ID>',
  site: '<PUBLIC_DATAWAY_URL>',
  clientToken: '<CLIENT_TOKEN>',
  env: 'production',
  version: '1.0.0',
  service: 'miniapp',
  sampleRate: 100,
  trackInteractions: true,
  traceType: 'ddtrace',
  allowedTracingUrls: ['https://api.example.com/v1/'],
})
datafluxRum.init({
  applicationId: '<APPLICATION_ID>',
  datakitOrigin: '<DATAKIT_ORIGIN>',
  env: 'production',
  version: '1.0.0',
  service: 'miniapp',
  sampleRate: 100,
  trackInteractions: true,
  traceType: 'ddtrace',
  allowedTracingUrls: ['https://api.example.com/v1/'],
})

Replace the placeholders with the actual configuration of the current application. For allowedTracingUrls, enter only the business API addresses for which trace correlation is required. You can remove it if distributed tracing is not required.

Verify Integration

  1. Check that the domain corresponding to the selected reporting address has been added to the request legal domains of the WeChat Mini Program.
  2. Open the Mini Program, trigger a page view, button click, and business request, and confirm in Developer Tools that successful RUM reporting requests exist and that there are no domain verification or SDK initialization errors.
  3. Go to "RUM > Application List", open the corresponding Mini Program application, and confirm that the Explorer contains data such as View, Resource, or Action.
  4. Before release, verify network connectivity and data reporting on a real device. Do not rely only on the debugging configuration in Developer Tools.

If there is no data, first confirm that applicationId matches the current Mini Program application, and then check the parameters for the selected reporting method, the request legal domains, and sampleRate.

Configuration

Initialization Parameters

Parameter Type Required Default Description
applicationId String Yes Application ID created in TrueWatch.
datakitOrigin String When using local environment deployment DataKit data reporting address. Configure only for local environment deployment; the corresponding domain must be added to the request legal domains in the Mini Program admin console.
site String When using public DataWay Public DataWay address of the current site. Copy it from the application integration configuration; the corresponding domain must be added to the request legal domains in the Mini Program admin console.
clientToken String When using public DataWay Client Token used for reporting to public DataWay, generated when the application is created in the console.
env String No Current environment of the Mini Program application, e.g., prod: production environment; gray: canary environment; pre: staging environment; common: daily environment; local: local environment.
version String No Version number of the Mini Program application.
service String No Service name of the current application. The default is miniapp and custom configuration is supported.
sampleRate Number No 100 Metric data collection percentage: 100 means collect all, and 0 means collect none.
sessionSampleRate Number No 100 Compatibility alias for sampleRate. If both are set, sampleRate takes precedence.
remoteConfiguration Boolean No false Whether to enable Remote Configuration. The SDK starts with the local configuration first, then asynchronously fetches and applies supported configuration items.
remoteConfigration Boolean No false Legacy spelling compatibility option for remoteConfiguration; not recommended for new projects.
remoteConfigurationFetchTimeout Number No 3000 Timeout for remote configuration requests, in milliseconds. If the request fails or times out, the local configuration continues to be used.
trackInteractions Boolean No false Whether to enable user behavior collection.
trackResourceQueryString Boolean No false Whether to collect the query string of the request URL. The query string may contain tokens or user IDs; enable this only after confirming it is safe.
trackRequestErrorResponseBody Boolean No false Whether to write the response body of failed requests to the error stack. The response body may contain sensitive data.
requestErrorResponseLengthLimit Number No 32768 Maximum number of characters from a failed request response body that can be written to the error stack. This takes effect only after trackRequestErrorResponseBody is enabled.
trackLaunchOptions Boolean No false Whether to collect query and referrerInfo from the Mini Program launch parameters.
beforeSend Function No Callback before data enters the sending queue, which can modify events; returning false can discard non-View events. Callback exceptions do not interrupt the business or the SDK.
userId / user_id String No Set the logged-in user ID during initialization; you can also call setUser({ id }) after initialization.
traceType Enum No ddtrace Configures the distributed tracing tool type. If not configured, the default is ddtrace. Currently, 6 data types are supported: ddtrace, zipkin, skywalking_v3, jaeger, zipkin_single_header, and w3c_traceparent.
❗️
1. opentelemetry supports 4 types: zipkin_single_header, w3c_traceparent, zipkin, and jaeger.
2. To configure a traceType of the corresponding type, you need to set different Access-Control-Allow-Headers for the corresponding API service. For details, see How APM correlates with RUM.
traceId128Bit Boolean No false Whether to generate a 128-bit traceID. This corresponds to traceType and currently supports zipkin and jaeger.
allowedTracingUrls Array No [] List of full request URL matches allowed to inject Trace Headers. Strings match by URL prefix; regular expressions and functions receive the full URL; objects use { match, traceType } to specify the propagation type for a single rule. Requires version 2.2.19 or later.
allowedTracingOrigins Array No Deprecated compatibility configuration that matches only the request Origin exactly; new projects should use allowedTracingUrls. If both are set, allowedTracingUrls takes precedence.
allowTraceHeaderWithoutSession Boolean No false Whether to still inject Trace Headers into requests that match allowedTracingUrls when the current Session is not sampled. When enabled, this does not force sampling or report RUM data for that Session.
isIntakeUrl Function No function(url) {return false} Custom method that determines whether to collect data for the corresponding resource based on the requested resource URL. By default, all resources are collected. Return value: false means collect, and true means do not collect.
❗️
1. The return value of this parameter method must be of Boolean type; otherwise, the parameter is considered invalid.
2. Requires version 2.1.10 or later.

Trace Header URL Matching

allowedTracingUrls uses full request URL matching. Strings use prefix matching, and RegExp and Function receive the full URL. To specify a different propagation type for a rule, use an object that contains both match and traceType:

allowedTracingUrls: [
  'https://api.example.com/v1/',
  /https:\/\/.*\.my-api-domain\.com\/v2\//,
  function (url) {
    return url.indexOf('https://internal.example.com/') === 0
  },
  { match: 'https://otel.example.com/', traceType: 'w3c_traceparent' },
]

allowedTracingOrigins is used only for compatibility with legacy configurations: both strings and regular expressions match against the request Origin. If both parameters are configured, the SDK uses only allowedTracingUrls.

Trace Headers for Unsampled Sessions

allowTraceHeaderWithoutSession defaults to false. When set to true, even if the current Session is not sampled by RUM, the SDK still injects Trace Headers into requests that match allowedTracingUrls. This configuration does not force sampling or create a new Session, and it does not report RUM data such as View, Action, Resource, or Error for unsampled Sessions.

Notes

  1. Add the domain corresponding to the actual reporting address (site for public DataWay, or datakitOrigin for local environment deployment) to the request legal domains in the Mini Program admin console.
  2. Currently, on iOS, the WeChat Mini Program resource request APIs wx.request and wx.downloadFile do not support returning the profile field in their response data. As a result, timing-related data in the collected resource information may be incomplete. There is currently no solution: request, downloadFile, API support status.
  3. After trackInteractions user behavior collection is enabled, due to WeChat Mini Program limitations, the content and structure data of controls cannot be collected. Therefore, in the Mini Program SDK, we use declarative programming: by setting the data-name attribute in the wxml file, you can add a name to interactive elements, making it easier to locate operation records during subsequent analytics. For example:
<button bindtap="bindSetData" data-name="setData">
  setData
</button>