All Products
Search
Document Center

Simple Log Service:Use the STS plug-in of web tracking SDK for JavaScript to upload logs

Last Updated:Oct 10, 2026

The STS plug-in of web tracking SDK for JavaScript uses Alibaba Cloud Security Token Service (STS) temporary credentials to upload logs without enabling the web tracking feature for the Logstore, which helps prevent dirty data.

Background information

image

Without STS temporary authorization, you must enable the web tracking feature for the Logstore, which allows anonymous writes from browsers and may generate dirty data. The following steps describe how the STS plug-in uploads logs:

  1. A browser requests a temporary identity credential (STS token) from a business server.

  2. The service server requests an STS token from the STS service.

    1. An AccessKey pair of the Resource Access Management (RAM) user is configured in the server and the RAM user is attached the AliyunSTSAssumeRoleAccess policy.

    2. The server uses the AccessKey pair of the RAM user to call the AssumeRole operation of STS to obtain the STS token of the RAM role. You can use the Policy parameter of AssumeRole to restrict the permissions of different STS tokens based on the user or device.

  3. STS returns an STS token to the business server.

  4. The service server returns an STS token to the browser.

  5. The browser uses the obtained STS token to assume the RAM role and uploads logs collected from the browser to the Logstore.

  6. Simple Log Service returns a response to the browser after the log is uploaded.

Prerequisites

Step 1: Install and configure the SDK

Important
  • The npm method is used in this topic to install the web tracking SDK for JavaScript to collect website logs. If you want to use the Alibaba Cloud CDN method, see WebTracking JavaScript SDK.

  1. Install Node.js.

  2. Run the following command on the business server to install dependencies.

    npm install --save @aliyun-sls/web-track-browser
    npm install --save @aliyun-sls/web-sts-plugin
  3. Add the following code to your program to configure the SDK.

    import SlsTracker from '@aliyun-sls/web-track-browser'
    import createStsPlugin from '@aliyun-sls/web-sts-plugin'
    
    const opts = {
      host: '${host}', // The Simple Log Service endpoint for the region. Example: cn-hangzhou.log.aliyuncs.com.
      project: '${project}', // The name of the project. 
      logstore: '${logstore}', // The name of the Logstore. 
      time: 10, // The interval at which logs are sent. Default value: 10. Unit: seconds. 
      count: 10, // The maximum number of logs that can be sent in each request. Default value: 10. 
      topic: 'topic',// The custom topic of logs. 
      source: 'source',
      tags: {
        tags: 'tags',
      },
    }
    
    const stsOpt = {
      accessKeyId: '',
      accessKeySecret: '',
      securityToken: '',
      // The following is a simple example of an STS token refresh function.
      refreshSTSToken: () =>
        new Promise((resolve, reject) => {
          const xhr = new window.XMLHttpRequest()
            xhr.open('GET', 'localhost:7000/test/sts', true)
            xhr.send()
            xhr.onreadystatechange = () => {
              if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                  let credential = JSON.parse(xhr.response)
                  // The purpose of the function is to configure the temporary key and token of stsOpt. 
                  stsOpt.accessKeyId = credential.AccessKeyId
                  stsOpt.accessKeySecret = credential.AccessKeySecret
                  stsOpt.securityToken = credential.SecurityToken
                  resolve()
                } else {
                  reject('Wrong status code.')
                }
              }
            }
          }),
      // refreshSTSTokenInterval: 300000,
      // stsTokenFreshTime: undefined,
    }
    
    // Create a tracker.
    const tracker = new SlsTracker(opts)
    // Create the STS plug-in.
    const stsPlugin = createStsPlugin(stsOpt)
    // Use the STS plug-in.
    tracker.useStsPlugin(stsPlugin)
    
    // Assume that you want to upload a single log.
    tracker.send({
      eventType:'view_product',
      productName: 'Tablet',
      price: 500
    })
    

    The following table describes the web tracking parameters.

    Parameter

    Required

    Description

    host

    Yes

    The endpoint of the region where Simple Log Service resides. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint. For more information, see Endpoints.

    project

    Yes

    The name of the project.

    logstore

    Yes

    The name of the Logstore.

    time

    No

    The interval at which logs are sent. Default value: 10. Unit: seconds.

    count

    No

    The maximum number of logs that can be sent in each request. Default value: 10.

    topic

    No

    The topic of logs. Specify a custom value to identify logs.

    source

    No

    The source of logs. Specify a custom value to identify logs.

    tags

    No

    Custom tags to identify logs.

    The following table describes the STS parameters.

    Parameter

    Required

    Description

    • accessKeyId

    • accessKeySecret

    • securityToken

    Yes

    • The business server uses the AccessKey pair of the RAM user to call the AssumeRole operation. The response parameters include AccessKeySecret, AccessKeyId, and SecurityToken.

    • In the input parameters of the AssumeRole operation, DurationSeconds specifies the validity period of the token and Policy specifies the permission scope of the token.

    refreshSTSToken

    Yes

    A function that periodically obtains new STS tokens to update the credential fields. Supports Promise and async functions.

    refreshSTSTokenInterval

    No

    The interval at which tokens are refreshed, in milliseconds. Default value: 300,000 (5 minutes).

    stsTokenFreshTime

    No

    The timestamp of the most recent token acquisition. You do not need to set this parameter.

Step 2: Upload logs

When you upload a single log, the log is uploaded as a separate object. When you upload multiple logs, the logs are uploaded as an array that contains multiple objects.

  • Upload a single log. The type is object. Example:

    tracker.send({
      eventType:'view_product',
      productName: 'Tablet',
      price: 500
    })
  • Immediately upload a single log. The time and count parameters do not take effect. The type is object. Example:

    tracker.sendImmediate({
      eventType:'view_product',
      productName: 'Tablet',
      price: 500
    })
  • Upload multiple logs at a time. The type is array. Example:

    tracker.sendBatchLogs([
      {
        eventType: 'view_product',
        productName: 'Tablet',
        price: 500
      },
      {
        eventType: 'view_product',
        productName: 'Laptop',
        price: 1200
      }
    ])
  • Immediately upload multiple logs at a time. The time and count parameters do not take effect. The type is array. Example:

    tracker.sendBatchLogsImmediate([
      {
        eventType:'view_product',
        productName: 'Tablet',
        price: 500
      },
      {
        eventType:'view_product',
        productName: 'Laptop',
        price: 1200
      }
    ])

Step 3: View the upload result

You can view the upload result by using the console or calling API operations.

console:

  1. Log on to the Simple Log Service console.

  2. In the Projects section, click the project you want.

  3. On the Log Storage > Logstores tab, click the logstore you want. Then click Consumption Preview to view the logs.

API:

  1. Call the CreateIndexoperation to create full-text indexes or field indexes. If you want to use the SELECT statement, you must create field indexes.

  2. Call the GetLogsV2operation to query logs in a logstore. The returned result is an array of logs. Each element in the array is a log.

References

  • This topic uses the web tracking SDK for JavaScript to collect website logs. For more information about how to use web tracking SDK for JavaScript to collect mini program logs, see WebTracking JavaScript SDK for mini programs.

FAQ

The SDK starts without errors, but when sending logs, it reports the TypeError: Cannot read properties of undefined (reading 'sigBytes'). What do I do if this issue occurs?

Possible cause: a CryptoJS encryption issue. Because the third-party package is difficult to modify, we recommend using web tracking for unauthenticated writes. For more information, see Collect client-side logs with WebTracking.