tencent cloud

Getting Started
Last updated:2026-03-03 15:47:44
Getting Started
Last updated: 2026-03-03 15:47:44

Relevant Resources

For SDK source code download, see React Native source code download.
For the sample Demo, see React Native SDK Demo.
For the SDK change log, see CHANGELOG.
For the npm address, see npm address.

Environment Configuration and Preparation

You need a pure React Native project or a React Native-native hybrid project. This application can be your existing project or a new empty project you created. For details, see React Native app development guide.
React Native version requirements: 0.69.7 or higher.

Installing the SDK

react-Native-cos-sdk currently supports iOS and Android, and is implemented by bridging the Native Android and iOS COS SDKs.
1. Run the following command:
Using npm:
npm install --save react-native-cos-sdk
Or use yarn:
yarn add react-native-cos-sdk
2. In your code, you can use import to import and then start using:
import Cos from 'react-native-cos-sdk';
Note:
To continuously track and optimize the quality of the SDK and provide you with a better user experience, we have introduced the Tencent Beacon SDK. Tencent Beacon only monitors the request performance on the COS side and will not report business-side data.
If you want to disable this feature, you can replace react-native-cos-sdk with react-native-cos-sdk-nobeacon during dependency import and import.

Initialize COS Service

Note:
It is recommended that users use temporary keys to call the SDK, which further enhances security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of resources beyond the target bucket or objects.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the scope of permissions for the permanent keys.
For your business security, please refer to Upload Security Restrictions for file uploads.

Set API Access Key

Single-Use Temporary Key
Temporary Key Callback
Fixed Key (for testing only)
Set the individual key to the sessionCredentials parameter of specific COS operation methods (such as the upload method), and this key is only used for the current COS operation (such as upload and so on).
// Obtain temporary keys (controlled at the business layer)
let tmpSecretId = "SECRETID"; // Temporary key SecretId
let tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
let sessionToken = "SESSIONTOKEN"; // Temporary key Token
let expiredTime = 1556183496;//Expiration timestamp of the temporary key, in seconds
// It is recommended to return the server time as the signature start time to prevent request expiration due to excessive local time deviation on the user's device
let startTime = 1556182000; // Temporary key validity start time, in seconds
const sessionCredentials = {
tmpSecretId: tmpSecretId,
tmpSecretKey: tmpSecretKey,
startTime: startTime,
expiredTime: expiredTime,
sessionToken: sessionToken
};
// Subsequently, pass sessionQCloudCredentials to specific COS operation methods
Note:
COS SDK version needs to be greater than or equal to v1.1.9.
Provide a callback method to the COS SDK for obtaining temporary keys. The SDK will use this callback to retrieve temporary keys when first initialized and when the cached temporary keys are about to expire.
Call the initWithSessionCredentialCallback method of Cos to implement the process of requesting temporary keys and returning the result.
import Cos from 'react-native-cos-sdk';

Cos.initWithSessionCredentialCallback(async () => {
// First, obtain the response containing key information from your temporary key server, for example:
// url for the temporary key server. For the temporary key generation service, see https://www.tencentcloud.com/document/product/436/14048
let stsUrl = "http://stsservice.com/sts";
let response = null;
try{
response = await fetch(stsUrl);
} catch(e){
console.error(e);
return null;
}
// Then parse the response to obtain temporary key information
const responseJson = await response.json();
const credentials = responseJson.credentials;
const startTime = responseJson.startTime;
const expiredTime = responseJson.expiredTime;
const sessionCredentials = {
tmpSecretId: credentials.tmpSecretId,
tmpSecretKey: credentials.tmpSecretKey,
startTime: startTime, // startTime is a 10-digit timestamp.
expiredTime: expiredTime, // expiredTime is a 10-digit timestamp.
sessionToken: credentials.sessionToken
};
console.log(sessionCredentials);
// Finally, return the temporary key information object
return sessionCredentials;
})
You can use Tencent Cloud's permanent keys for local debugging during development. Due to risks of key leakage, you must replace them with temporary keys before deployment.
import Cos from 'react-native-cos-sdk';

let SECRET_ID = "SECRETID"; // Permanent key secretId
let SECRET_KEY = "SECRETKEY"; // Permanent key secretKey

Cos.initWithPlainSecret(
SECRET_ID,
SECRET_KEY
)

Register for the COS Service

// The abbreviation for the bucket region, such as ap-guangzhou for Guangzhou
let region = "COS_REGION";
// Create a CosXmlServiceConfig object and modify the default configuration parameters as needed
let serviceConfig = {
region: region,
isDebuggable: true,
isHttps: true,
};
// Register the default COS Service
let cosService = await Cos.registerDefaultService(serviceConfig);
// Obtain the default COS Service
let cosService1 = Cos.getDefaultService();

// Create a TransferConfig object and modify the default configuration parameters as needed
// TransferConfig allows you to set the intelligent chunking threshold. By default, files larger than or equal to 2MB are automatically uploaded in chunks. You can modify the chunking threshold with the following code.
let transferConfig = {
forceSimpleUpload: false,
enableVerification: true,
divisionForUpload: 2097152, // Set files larger than or equal to 2MB to be uploaded in chunks
sliceSizeForUpload: 1048576, // Set the default chunk size to 1MB
};
// Register the default COS TransferManger
let cosTransferManger = await Cos.registerDefaultTransferManger(serviceConfig, transferConfig);
// Obtain the default COS TransferManger
let cosTransferManger1 = Cos.getDefaultTransferManger();

// You can also register other instances using registerService and registerTransferManger for subsequent calls.
// Generally, region is used as the registration key
let newRegion = "NEW_COS_REGION";
serviceConfig.region = newRegion;
let cosServiceNew = await Cos.registerService(newRegion, serviceConfig);
let cosTransferMangerNew = await Cos.registerTransferManger(newRegion, serviceConfig, transferConfig);
// Obtain COS Service and COS TransferManger via key
let cosServiceNew1 = Cos.getService(newRegion);
let cosTransferMangerNew1 = Cos.getTransferManger(newRegion);
Note:
Before COS Service and COS TransferManger are obtained, registration must be performed; otherwise, an error will be reported.
For example, you can control the process where registration is mandatory before they are obtained by encapsulating a method similar to the following:
const SERVICE_CONFIG = {
region: "COS_REGION",
isDebuggable: true,
}

export async function getDefaultService(): Promise<CosService> {
if(Cos.hasDefaultService()){
return Cos.getDefaultService()
} else {
// Register the default service
return await Cos.registerDefaultService(SERVICE_CONFIG)
}
}

Parameter Description

CosXmlServiceConfig configures the COS service, and its main members are described as follows:
Parameter Name
Description
Type
Default Value
Supported Platforms
region
The region of the bucket. For details, see Regions and Access Domains
String
null
Android and iOS
connectionTimeout
Connection timeout time (in milliseconds)
Int
Android(15000)
iOS(30000)
Android and iOS
socketTimeout
Read/write timeout time (in milliseconds)
Int
30000
Android
isHttps
Whether to use the https protocol
Bool
true
Android and iOS
host
Set the host for all requests except GetService.
String
null
Android and iOS
hostFormat
Set the format string for the host. The sdk will replace ${bucket} with the actual bucket and ${region} with the actual region.
For example, if you set hostFormat to ${bucket}.${region}.tencent.com, and your bucket and region are bucket-1250000000 and ap-shanghai respectively, the final request address will be bucket-1250000000.ap-shanghai.tencent.com
Note:
This setting does not affect GetService requests.
String
null
Android
port
Set the request port.
Int
null
Android
isDebuggable
whether it is in debug mode (debug mode prints debug logs)
Bool
false
Android
signInUrl
Whether to place the signature in the URL, which is placed in the Header by default.
Bool
false
Android
userAgent
ua extension parameters
String
null
Android and iOS
dnsCache
Whether to enable DNS resolution caching. When DNS resolution caching is enabled, the DNS resolution results are cached locally. If the system DNS resolution fails, the locally cached DNS results will be used.
Bool
true
Android
accelerate
Whether to use Global Accelerator domain names.
Bool
false
Android and iOS
TransferConfig configures the COS upload service, and its main members are described as follows:
Parameter Name
Description
Type
Default Value
Supported Platforms
divisionForUpload
Set the minimum object size for chunked upload.
Int
2097152
Android and iOS
sliceSizeForUpload
Set the part size for chunked upload.
Int
1048576
Android and iOS
enableVerification
Whether to verify the integrity during chunked upload
Bool
true
Android and iOS
forceSimpleUpload
Whether to force the use of simple upload.
Bool
false
Android

Access COS Service

PUT Object
Downloading an Object
Note:
For more complete examples, visit GitHub.
// Obtain CosTransferManger
let cosTransferManger: CosTransferManger = Cos.getDefaultTransferManger();
//let cosTransferManger: CosTransferManger = Cos.getTransferManger(newRegion);
// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucket
let bucket = "examplebucket-1250000000";
let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
let srcPath = "local file path"; // local file path
// If an UploadId for an initialized multipart upload exists, assign its value to uploadId for resuming; otherwise, assign undefined
let _uploadId = undefined;

// Upload success callback
let successCallBack = (header?: object) => {
// todo Upload success follow-up logic
};
// Upload failure callback
let failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {
// todo Upload failure follow-up logic
if (clientError) {
console.log(clientError);
}
if (serviceError) {
console.log(serviceError);
}
};
// Upload status callback, which allows you to view the task progress
let stateCallBack = (state: TransferState) => {
// todo notify transfer state
};
// Upload progress callback
let progressCallBack = (complete: number, target: number) => {
// todo Do something to update progress...
};
// Initialization chunk complete callback
let initMultipleUploadCallBack = (bucket: string, cosKey: string, uploadId: string) => {
// Used to resume the upload next time, uploadId
_uploadId = uploadId;
};

// Start upload
let transferTask:TransferTask = await cosTransferManger.upload(
bucket,
cosPath,
srcPath,
{
uploadId: _uploadId,
resultListener: {
successCallBack: successCallBack,
failCallBack: failCallBack
},
stateCallback: stateCallBack,
progressCallback: progressCallBack,
initMultipleUploadCallback: initMultipleUploadCallBack,
// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parameter
sessionCredentials: sessionCredentials
}
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();
Note:
For more complete examples, visit GitHub.
// The advanced download API supports resuming from breakpoints, so it initiates a HEAD request to obtain file information before downloading.
// If you are using a temporary key or accessing with a sub-account, ensure that the permission list includes the HeadObject permission.

// CosTransferManager supports resumable downloads; you only need to ensure the bucket, cosPath, and savePath
// If the parameters are consistent, the SDK will resume downloading from the last position.

// Obtain CosTransferManger
let cosTransferManger: CosTransferManger = Cos.getDefaultTransferManger();
//let cosTransferManger: CosTransferManger = Cos.getTransferManger(newRegion);
// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucket
let bucket = "examplebucket-1250000000";
let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
let downliadPath = "local file path"; // path to save the local file

// Download success callback
let successCallBack = (header?: object) => {
// todo Download success follow-up logic
};
// Download failure callback
let failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {
// todo Download failure follow-up logic
if (clientError) {
console.log(clientError);
}
if (serviceError) {
console.log(serviceError);
}
};
// Download status callback, which allows you to view the task progress
let stateCallBack = (state: TransferState) => {
// todo notify transfer state
};
// Download progress callback
let progressCallBack = (complete: number, target: number) => {
// todo Do something to download progress...
};

// Start download
let transferTask:TransferTask = await cosTransferManger.download(
bucket,
cosPath,
downliadPath,
{
resultListener: {
successCallBack: successCallBack,
failCallBack: failCallBack
},
stateCallback: stateCallBack,
progressCallback: progressCallBack,
// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parameter
sessionCredentials: sessionCredentials
}
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();

FAQs

You may encounter some common issues during use. For related solutions, see React Native SDK FAQ.
Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback