Alibaba Cloud Dysmsapi SDK for Node.js is the official SDK for Alibaba Cloud Short Message Service (SMS). It helps you integrate SMS capabilities, such as sending verification codes, marketing notifications, and international messages—into your TypeScript or Node.js applications.
Installation
System requirements
Node.js: Version 14.0 or later.
Operating System: Windows, macOS, or Linux.
Other dependencies: None. The SDK includes all required dependencies.
Install using npm
npm install @alicloud/dysmsapi20180501 -SVerify the installation
npm list @alicloud/dysmsapi20180501
# If the SDK version number is displayed, the installation was successful.Configure authentication
Step 1: Create a RAM user and grant permissions
Because your root account has high privileges, we recommend using a RAM user for API calls and routine O&M. For more information, see Overview of RAM users.
Create a RAM user: Go to the Create User page. Specify the required information, select Permanent AccessKey for Access Configuration, then click OK. Save your AccessKey for later use.
Grant permissions to the RAM User: Go to the Users page. Find the RAM user that you created and click Attach Policy in the Actions column. In the Policy search box, enter AliyunDysmsFullAccess, select the policy, and then click OK.
AliyunDysmsFullAccess: Grants full permissions to manage the SMS service.
AliyunDysmsReadOnlyAccess: Grants read-only permissions to access the SMS service.
If you need to create a custom policy, see RAM authorization.
Step 2: Obtain access credentials
Configure your AccessKey pair using environment variables. For information about how to configure environment variables, see Configure environment variables on Linux, macOS, and Windows.
To prevent security risks, avoid hard-coding your AccessKey pair. Instead, retrieve it from environment variables.
The sample code in this topic uses the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET.
Security best practices
Store credentials by using environment variables or a key management service.
Rotate your AccessKey pair on a regular basis.
Follow the principle of least privilege by granting the minimum required permissions to RAM Users.
Do not print credential information in logs.
Use a RAM Role instead of your root account credentials in production environments.
Quick start
Sample code
This sample code demonstrates how to call the SMS API to send messages. Replace the placeholder values as instructed in the code comments.
TypeScript:
/**
* Alibaba Cloud International SMS - TypeScript Version
* API: BatchSendMessageToGlobe
*
* Environment requirements: Node.js >= 8.x
* Install: npm install @alicloud/dysmsapi20180501 @alicloud/credentials
*/
import Dysmsapi20180501, * as $Dysmsapi20180501 from '@alicloud/dysmsapi20180501';
import * as $OpenApi from '@alicloud/openapi-client';
import * as $Util from '@alicloud/tea-util';
import Credential from '@alicloud/credentials';
export class InternationalSmsClient {
/**
* Create an SMS client
* Use the credential chain to automatically obtain access credentials (supports environment variables, configuration files, and other methods).
* For credential configuration details, see: https://www.alibabacloud.com/help/document_detail/378664.html
*/
static createClient(): Dysmsapi20180501 {
const config = new $OpenApi.Config({
credential: new Credential(),
endpoint: 'dysmsapi.aliyuncs.com'
});
return new Dysmsapi20180501(config);
}
/**
* Batch send international text messages
* @param to - Recipient number (international format, such as: +1234567890)
* @param from - Sender number
* @param message - Text message content
*/
static async batchSendMessage(to: string, from: string, message: string): Promise<void> {
const client = this.createClient();
const request = new $Dysmsapi20180501.BatchSendMessageToGlobeRequest({
to,
from,
message
});
try {
const response = await client.batchSendMessageToGlobeWithOptions(
request,
new $Util.RuntimeOptions({})
);
console.log('Text message sent successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error: any) {
console.error('Failed to send text message:', error.message);
if (error.data?.Recommend) {
console.error('Diagnostic recommendations:', error.data.Recommend);
}
throw error;
}
}
}
// Command line invocation example
if (require.main === module) {
const [to, from, message] = process.argv.slice(2);
if (!to || !from || !message) {
console.error('Usage: ts-node international-sms-typescript.ts <to> <from> <message>');
console.error('Example: ts-node international-sms-typescript.ts "+1234567890" "sender" "Hello World"');
process.exit(1);
}
InternationalSmsClient.batchSendMessage(to, from, message)
.catch(error => {
console.error('Execution failed:', error);
process.exit(1);
});
}
JavaScript:
/**
* Alibaba Cloud International SMS - Node.js Version
* API: BatchSendMessageToGlobe
*
* Environment requirements: Node.js >= 8.x
* Install: npm install @alicloud/dysmsapi20180501 @alicloud/credentials
*/
'use strict';
const Dysmsapi20180501 = require('@alicloud/dysmsapi20180501');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
class InternationalSmsClient {
/**
* Create an SMS client
* Use the credential chain to automatically obtain access credentials (supports environment variables, configuration files, and other methods).
* For credential configuration details, see: https://www.alibabacloud.com/help/document_detail/378664.html
*/
static createClient() {
const config = new OpenApi.Config({
credential: new Credential.default(),
endpoint: 'dysmsapi.aliyuncs.com'
});
return new Dysmsapi20180501.default(config);
}
/**
* Batch send international text messages
* @param {string} to - Recipient number (international format, such as: +1234567890)
* @param {string} from - Sender number
* @param {string} message - Text message content
*/
static async batchSendMessage(to, from, message) {
const client = this.createClient();
const request = new Dysmsapi20180501.BatchSendMessageToGlobeRequest({
to,
from,
message
});
try {
const response = await client.batchSendMessageToGlobeWithOptions(
request,
new Util.RuntimeOptions({})
);
console.log('Text message sent successfully');
console.log(JSON.stringify(response, null, 2));
return response;
} catch (error) {
console.error('Failed to send text message:', error.message);
if (error.data?.Recommend) {
console.error('Diagnostic recommendations:', error.data.Recommend);
}
throw error;
}
}
}
// Command line invocation example
if (require.main === module) {
const [to, from, message] = process.argv.slice(2);
if (!to || !from || !message) {
console.error('Usage: node international-sms-nodejs.js <to> <from> <message>');
console.error('Example: node international-sms-nodejs.js "+1234567890" "sender" "Hello World"');
process.exit(1);
}
InternationalSmsClient.batchSendMessage(to, from, message)
.catch(error => {
console.error('Execution failed:', error);
process.exit(1);
});
}
module.exports = { InternationalSmsClient };
Download the sample code
You can also download the sample code and run it directly.
Go to SendMessageToGlobe.
On the Parameters tab on the left, specify the required parameters. The following are example values:
To: 88691567****
Message: This is a test message.
Best practices
Performance optimization
Connection reuse: The SDK uses an HTTP connection pool by default. No additional configuration is required.
Asynchronous processing: Sending messages is an asynchronous operation. Do not block the main thread.
Retry: Implement an exponential backoff retry strategy for temporary errors, such as network timeouts.
Security recommendations
Credential management: Store credentials in environment variables or use the Key Management Service.
Least privilege: Create separate RAM users for different applications and grant least privilege access.
Input validation: Strictly validate and sanitize user input, such as phone numbers and template parameters.
Log masking: Mask sensitive information in logs, such as the middle four digits of phone numbers and CAPTCHA.
Resource management
Client reuse: Reuse the same Client instance throughout the application lifecycle. Avoid frequent creation and destruction.
Error handling: Categorize and handle exceptions thrown by the SDK. Distinguish between business errors and system errors.
Monitoring and alerts: Record key metrics, such as send success rate, response time, and QPS. Set up monitoring and alerts.
References
GitHub repository: Alibaba Cloud Dysmsapi SDK for NodeJS
API reference:
Before you call an OpenAPI operation, we recommend that you read the related API reference, such as SendMessageToGlobe, to understand the required parameters, permissions, and other details. For more information, see API overview.
Call an API:
The SDK is the recommended way to call an API. This topic uses the TypeScript/Node.js SDK as an example. SDK usage in other languages is similar. For more information, see SMS SDK.