All Products
Search
Document Center

Object Storage Service:Initialize an OSSClient instance for OSS SDK for Browser.js

Last Updated:Nov 22, 2024

OSSClient is the Browser.js client of Object Storage Service (OSS). It is used to manage OSS resources, such as buckets and objects. To use OSS SDK for Browser.js to initiate a request, you must initialize an OSSClient instance and modify the default configuration items of the ClientConfiguration configuration class based on your business requirements.

Prerequisites

OSS SDK for Browser.js is installed. For more information, see Installation.

Create an OSSClient instance

(Recommended) Use the V4 signature algorithm

We recommend that you use the V4 signature algorithm which provides better security. In this case, you must declare authorizationV4. OSS SDK for Browser.js 6.20.0 and later support the V4 signature algorithm.

The following sample code provides an example on how to use an OSS endpoint to create an OSSClient instance by using the V4 signature algorithm. If you want to use other methods to create an OSSClient instance by using the V4 signature algorithm, refer to the following sample code and change the variables.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.20.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: 'yourRegion',
	authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Specify the security token obtained from STS. 
        stsToken: 'yourSecurityToken',
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });
    </script>
  </body>
</html>

(Not recommended) Use the V1 signature algorithm

Important

From December 1, 2024, the V1 signature algorithm of OSS is no longer available to new customers with new UIDs. From June 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: 'yourRegion',
        // Specify the temporary AccessKey pair obtained from STS. 
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Specify the security token obtained from STS. 
        stsToken: 'yourSecurityToken',
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });
    </script>
  </body>
</html>

Configure an OSSClient instance

When you initialize an OSSClient instance, you can specify parameters based on your business requirements. For example, you can specify a request timeout period by specifying timeout or temporary access credentials by specifying stsToken. For more information about the parameters and configuration examples supported by OSS SDK for Browser.js, refer to the following items.

Parameters:

  • accessKeyId {String}: the AccessKey ID that is created in the Alibaba Cloud Management Console.

  • accessKeySecret {String}: the AccessKey secret that is created in the Alibaba Cloud Management Console.

  • [stsToken] {String}: the security token used for temporary authorization.

  • [refreshSTSToken] {Function}: the function that automatically refreshes stsToken, accessKeyId, and accessKeySecret when the security token obtained from STS expires. The return value must be an object that contains stsToken, accessKeyId, and accessKeySecret.

  • [refreshSTSTokenInterval] {number}: the interval at which the security token obtained from STS is refreshed. Unit: milliseconds. It should be shorter than the validity period of the security token obtained from STS. The default value is 300000, which is equal to 5 minutes.

  • [bucket] {String}: the name of the default bucket that you want to access. If you do not have a bucket, call putBucket() to create a bucket.

  • [endpoint] {String}: the endpoint of the region in which the bucket is located. This parameter takes precedence over the region parameter. You can set the parameter to a public endpoint, an internal endpoint, or an acceleration endpoint based on your business requirements.

  • [region] {String}: the region in which the bucket is located. Default value: oss-cn-hangzhou.

  • [internal] {Boolean}: specifies whether to access OSS over the internal network. Default value: false. If your cloud server is deployed on Alibaba Cloud, you can set this parameter to true to reduce significant costs.

  • [secure] {Boolean}: specifies whether the OSS client uses HTTPS(secure: true) or HTTP(secure: false).

  • [timeout] {String|Number}: the instance-level timeout period for all operations. Default value: 60. Unit: seconds.

  • [cname] {Boolean}: specifies whether to use a custom domain name to access OSS. Default value: false. If you set this parameter to true, you can set the endpoint parameter to a custom domain name.

  • [isRequestPay] {Boolean}: specifies whether to enable pay-by-requester for the bucket. If the value is true, the 'x-oss-request-payer: 'requester' header is sent to the OSS server. Default value: false.

  • [useFetch] {Boolean}: specifies whether to enable fetch. This parameter takes effect only in browsers. Default value: false. If this parameter is set to true, the object is uploaded in fetch mode. Otherwise, XMLHttpRequest is used.

  • [enableProxy] {Boolean}: specifies whether to enable proxy requests. Default value: false. Before you enable proxy requests, make sure that proxy-agent is installed.

  • [proxy] {String | Object}: the proxy URI or option. Default value: null.

  • [retryMax] {Number}: the maximum number of retries when a request fails due to a network error or timeout. Streaming upload (such as put, putStream, and append) is not supported because a stream can be used only once.

  • [maxSockets] {Number}: the maximum number of sockets allowed per host. By default, the maximum number is not limited.

  • [authorizationV4] {Boolean}: specifies whether to use the V4 signature. Default value: false.

Examples

  • Basic structure

const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  region: 'oss-cn-hangzhou',
});
  • Use an acceleration endpoint

Note

Global acceleration endpoint: oss-accelerate.aliyuncs.com

Acceleration endpoint for regions outside the Chinese mainland: oss-accelerate-overseas.aliyuncs.com

const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  endpoint: 'oss-accelerate.aliyuncs.com',
});
  • Use a custom domain name

const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  cname: true,
  endpoint: 'your custome domain',
});
  • Use a security token

const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your STS key',
  accessKeySecret: 'your STS secret',
  stsToken: 'your STS token',
  refreshSTSToken: async () => {
    const info = await fetch('you sts server');
    return {
      accessKeyId: info.accessKeyId,
      accessKeySecret: info.accessKeySecret,
      stsToken: info.stsToken ,
    };
  },
  refreshSTSTokenInterval: 300000
});
  • Retry the request by using a stream

for (let i = 0; i <= store.options.retryMax; i++) {
  try {
    const result = await store.putStream('<example-object>', fs.createReadStream('<example-path>'));
    console.log(result);
    break; // break if success
  } catch (e) {
    console.log(e);
  }
}
  • Use a V4 signature: add headers to calculate the V4 signature by specifying the optional additionalHeaders option (type: string array) and include the value of the additionalHeaders option in the request headers

const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  bucket: 'your bucket name',
  region: 'oss-cn-hangzhou',
  authorizationV4: true ,
});

try {
  const bucketInfo = await store.getBucketInfo('your bucket name');
  console.log(bucketInfo);
} catch (e) {
  console.log(e);
}

try {
  const putObjectResult = await store.put('your bucket name', 'your object name', {
    headers: {
      // The headers of this request
      header1: 'value1',
      header2: 'value2' ,
    },
    // The keys of the request headers that need to be calculated into the V4 signature. Please ensure that these additional headers are included in the request headers.
    additionalHeaders: ['additional header1', 'additional header2'],
  });
  console.log(putObjectResult);
} catch (e) {
  console.log(e);
}