Alibaba Cloud Dysmsapi SDK for Node.js lets 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 bundles all required dependencies.
Install using npm
npm install @alicloud/dysmsapi20170525 -S
Verify the installation
npm list @alicloud/dysmsapi20170525
# If the SDK version number is displayed, the installation was successful.
Configure authentication
Step 1: Create a RAM user and grant permissions
Your root account has full permissions. Use a RAM user for API calls and routine O&M. For more information, see Overview.
-
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.
-
To create a custom policy, see RAM authorization.
Step 2: Configure access credentials
Store your AccessKey pair in environment variables. Configure environment variables on Linux, macOS, and Windows.
-
Do not hard-code your AccessKey pair. Retrieve it from environment variables.
-
The sample code uses the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET.
Step 3: Configure environment variables
Environment variables are the most secure and flexible method because they avoid hard-coding credentials and integrate easily with CI/CD pipelines.
Set the environment variables:
export ACCESS_KEY_ID='your_access_key_id'
export ACCESS_KEY_SECRET='your_access_key_secret'
Use in code:
TypeScript:
import { Client } from '@alicloud/dysmsapi20170525';
// Retrieve from environment variables.
const client = new Client({
accessKeyId: process.env.ACCESS_KEY_ID,
accessKeySecret: process.env.ACCESS_KEY_SECRET,
regionId: 'cn-hangzhou', // Select the region as needed.
});
JavaScript:
const { Client } = require('@alicloud/dysmsapi20170525');
// Retrieve from environment variables.
const client = new Client({
accessKeyId: process.env.ACCESS_KEY_ID,
accessKeySecret: process.env.ACCESS_KEY_SECRET,
regionId: 'cn-hangzhou', // Select the region as needed.
});
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
The following sample code calls the SMS API to send messages. Replace the placeholder values as instructed in the code comments.
TypeScript:
// Alibaba Cloud SMS SDK - TypeScript optimized version
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Credential from '@alicloud/credentials';
/**
* Create an SMS client.
* Use the default credential chain to read access credentials from environment variables or configuration files.
*/
function createClient(): Dysmsapi20170525 {
const credential = new Credential();
const config = new $OpenApi.Config({
credential,
endpoint: 'dysmsapi.aliyuncs.com',
});
return new Dysmsapi20170525(config);
}
/**
* Send a text message.
* @param phoneNumbers Mobile phone numbers (supports multiple, comma-separated).
* @param signName SMS signature.
* @param templateCode SMS template code.
* @param templateParam Template parameters (JSON string).
*/
async function sendSms(
phoneNumbers: string,
signName: string,
templateCode?: string,
templateParam?: string
): Promise<void> {
const client = createClient();
const request = new $Dysmsapi20170525.SendSmsRequest({
phoneNumbers,
signName,
templateCode,
templateParam,
});
try {
const response = await client.sendSms(request);
console.log('Sent successfully:', JSON.stringify(response, null, 2));
} catch (error: any) {
console.error('Failed to send:', error.message);
if (error.data?.Recommend) {
console.log('Diagnostic recommendations:', error.data.Recommend);
}
throw error;
}
}
// Example usage
sendSms(
'1380013xxxx', // Mobile phone number
'Alibaba Cloud', // Signature name
'SMS_123456', // Template code
'{"code":"123456"}' // Template parameters
);
JavaScript:
// Alibaba Cloud SMS SDK - Node.js optimized version
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Credential = require('@alicloud/credentials');
/**
* Create an SMS client.
* Use the default credential chain to read access credentials from environment variables or configuration files.
*/
function createClient() {
const credential = new Credential.default();
const config = new OpenApi.Config({
credential,
endpoint: 'dysmsapi.aliyuncs.com',
});
return new Dysmsapi20170525.default(config);
}
/**
* Send a text message.
* @param {string} phoneNumbers - Mobile phone numbers (supports multiple, comma-separated).
* @param {string} signName - SMS signature.
* @param {string} templateCode - SMS template code.
* @param {string} templateParam - Template parameters (JSON string).
*/
async function sendSms(phoneNumbers, signName, templateCode, templateParam) {
const client = createClient();
const request = new Dysmsapi20170525.SendSmsRequest({
phoneNumbers,
signName,
templateCode,
templateParam,
});
try {
const response = await client.sendSms(request);
console.log('Sent successfully:', JSON.stringify(response, null, 2));
} catch (error) {
console.error('Failed to send:', error.message);
if (error.data?.Recommend) {
console.log('Diagnostic recommendations:', error.data.Recommend);
}
throw error;
}
}
// Example usage
sendSms(
'1380013xxxx', // Mobile phone number
'Alibaba Cloud', // Signature name
'SMS_123456', // Template code
'{"code":"123456"}' // Template parameters
).catch(console.error);
module.exports = { createClient, sendSms };
Download the sample code
Download and run the sample code directly.
-
Go to SendSms.
-
On the Parameters tab, specify the required parameters. Example values:
-
PhoneNumbers: 139****0000
-
SignName: Alibaba Cloud Test
-
TemplateCode: SMS_15495****
-
TemplateParams:
{"code":"1234"}
Best practices
Performance optimization
-
Connection reuse: The SDK uses an HTTP connection pool by default, so no additional configuration is required.
-
Asynchronous processing: Message sending is asynchronous. Do not block the main thread.
-
Retry: Implement exponential backoff retries for transient errors such as network timeouts.
Security recommendations
-
Credential management: Store credentials in environment variables or in Key Management Service (KMS).
-
Least privilege: Create separate RAM users for different applications and grant only the minimum required permissions.
-
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 to avoid unnecessary creation overhead.
-
Error handling: Categorize exceptions from the SDK and handle business errors and system errors separately.
-
Monitoring and alerts: Track key metrics such as send success rate, response time, and QPS, and configure alerts accordingly.
FAQ
References
-
GitHub repository: Alibaba Cloud Dysmsapi SDK for NodeJS
-
API reference:
Review the API reference for each operation, such as SendSms, for required parameters and permissions.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. For SDKs in other languages, see SMS SDK.