Simple Message Queue (formerly MNS) Node.js SDK
The Simple Message Queue (formerly MNS) Node.js SDK supports queue-based messaging and topic-based pub/sub models. Use this SDK to create queues and topics, send and receive messages, and manage subscriptions programmatically.
Prerequisites
Before you begin, make sure you have:
An Alibaba Cloud account with an AccessKey pair. Store your AccessKey ID and AccessKey secret as environment variables. For more information, see Create an AccessKey pair
Node.js installed on your machine
A Simple Message Queue (formerly MNS) instance activated in the Alibaba Cloud console
Install the SDK
Install the package with npm:
npm install @alicloud/mns --saveOr with yarn:
yarn add @alicloud/mnsInitialize the client
Import the SDK and create a client instance with your account ID, endpoint, and credentials:
const MNSClient = require('@alicloud/mns');
const accountid = '<your-account-id>';
const client = new MNSClient(accountid, {
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
endpoint: 'https://<your-account-id>.mns.<region-id>.aliyuncs.com'
});Replace the following placeholders with your actual values:
Placeholder | Description | Example |
| Your Alibaba Cloud account ID |
|
| The region where your instance is deployed |
|
Find your endpoint on the Queue Details or Topic Details page in the console, under the Endpoint section.
Queue operations
The queue-based messaging model follows a producer-consumer pattern: a producer sends messages to a queue, and a consumer receives and processes them.
Create a queue
const queueName = 'test-queue';
const createRes = await client.createQueue(queueName, {
DelaySeconds: 0, // Delay before messages become visible (seconds)
MaximumMessageSize: 65536, // Maximum message size (bytes)
MessageRetentionPeriod: 345600, // How long messages are retained (seconds)
VisibilityTimeout: 30, // Visibility timeout after a receive (seconds)
PollingWaitSeconds: 0 // Long polling wait time (seconds)
});
console.log('Queue created:', createRes);Send a message
const sendRes = await client.sendMessage(queueName, {
MessageBody: 'hello <"aliyun-mns-nodejs-sdk">',
DelaySeconds: 0,
Priority: 8
});
console.log('Message sent:', sendRes.body);Send messages in a batch
const batchMessages = [
{ MessageBody: 'message 1', Priority: 8 },
{ MessageBody: 'message 2', Priority: 16 },
{ MessageBody: 'message 3', DelaySeconds: 10 }
];
const batchSendRes = await client.batchSendMessage(queueName, batchMessages);
console.log('Batch sent:', batchSendRes.body);Receive a message
Pass a wait time in seconds to enable long polling. The following call waits up to 30 seconds for a message to arrive:
const receiveRes = await client.receiveMessage(queueName, 30);
console.log('Message received:', receiveRes.body);Receive messages in a batch
Specify the maximum number of messages to receive and the long polling wait time:
// Receive up to 5 messages, wait up to 30 seconds
const batchReceiveRes = await client.batchReceiveMessage(queueName, 5, 30);
console.log('Batch received:', batchReceiveRes.body);Change the visibility timeout period
After receiving a message, extend its visibility timeout period to allow more processing time. This requires the receipt handle returned by the receive call:
const receiptHandle = receiveRes.body.ReceiptHandle;
const changeVisRes = await client.changeMessageVisibility(
queueName,
receiptHandle,
60 // New visibility timeout period (seconds)
);
console.log('Visibility timeout period updated:', changeVisRes.body);Delete a message
After processing a message, delete it from the queue using its receipt handle:
await client.deleteMessage(queueName, receiptHandle);
console.log('Message deleted');Delete messages in a batch
if (batchReceiveRes.body && batchReceiveRes.body.length > 0) {
const receiptHandles = batchReceiveRes.body.map(msg => msg.ReceiptHandle);
await client.batchDeleteMessage(queueName, receiptHandles);
console.log('Batch deleted');
}List queues
const listRes = await client.listQueue();
console.log('Queues:', listRes.body);Get queue properties
const attrRes = await client.getQueueAttributes(queueName);
console.log('Queue properties:', attrRes.body);Delete a queue
await client.deleteQueue(queueName);
console.log('Queue deleted');Complete queue example
The following example combines all queue operations into a single runnable script. It creates a queue, sends individual and batch messages, receives and deletes them, and cleans up the queue:
const MNSClient = require('@alicloud/mns');
async function queueExample() {
// Initialize the client
const client = new MNSClient('<your-account-id>', {
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
endpoint: 'https://<your-account-id>.mns.<region-id>.aliyuncs.com'
});
const queueName = 'test-queue';
try {
// Create a queue
const createRes = await client.createQueue(queueName, {
DelaySeconds: 0,
MaximumMessageSize: 65536,
MessageRetentionPeriod: 345600,
VisibilityTimeout: 30,
PollingWaitSeconds: 0
});
console.log('Queue created:', createRes);
// Wait for the queue to become available
await new Promise(resolve => setTimeout(resolve, 2000));
// Get queue properties
const attrRes = await client.getQueueAttributes(queueName);
console.log('Queue properties:', attrRes.body);
// Send a message
const sendRes = await client.sendMessage(queueName, {
MessageBody: 'hello <"aliyun-mns-nodejs-sdk">',
DelaySeconds: 0,
Priority: 8
});
console.log('Message sent:', sendRes.body);
// Send messages in a batch
const batchMessages = [
{ MessageBody: 'message 1', Priority: 8 },
{ MessageBody: 'message 2', Priority: 16 },
{ MessageBody: 'message 3', DelaySeconds: 10 }
];
const batchSendRes = await client.batchSendMessage(queueName, batchMessages);
console.log('Batch sent:', batchSendRes.body);
// Receive a message (long polling, 30-second wait)
const receiveRes = await client.receiveMessage(queueName, 30);
console.log('Message received:', receiveRes.body);
// Extend the visibility timeout period
const receiptHandle = receiveRes.body.ReceiptHandle;
const changeVisRes = await client.changeMessageVisibility(
queueName,
receiptHandle,
60
);
console.log('Visibility timeout period updated:', changeVisRes.body);
// Delete the message
await client.deleteMessage(queueName, receiptHandle);
console.log('Message deleted');
// Receive messages in a batch
const batchReceiveRes = await client.batchReceiveMessage(queueName, 5, 30);
console.log('Batch received:', batchReceiveRes.body);
// Delete messages in a batch
if (batchReceiveRes.body && batchReceiveRes.body.length > 0) {
const receiptHandles = batchReceiveRes.body.map(msg => msg.ReceiptHandle);
await client.batchDeleteMessage(queueName, receiptHandles);
console.log('Batch deleted');
}
// List queues
const listRes = await client.listQueue();
console.log('Queues:', listRes.body);
// Delete the queue
await client.deleteQueue(queueName);
console.log('Queue deleted');
} catch (err) {
console.error('Operation failed:', err);
}
}
queueExample();Topic operations
The topic-based model follows a pub/sub pattern: a publisher sends messages to a topic, and the topic pushes them to all subscribers.
Create a topic
const topicName = 'test-topic';
const topicRes = await client.createTopic(topicName, {
MaximumMessageSize: 65536,
LoggingEnabled: false
});
console.log('Topic created:', topicRes);Get topic properties
const attrRes = await client.getTopicAttributes(topicName);
console.log('Topic properties:', attrRes.body);Update topic properties
await client.setTopicAttributes(topicName, {
MaximumMessageSize: 32768
});
console.log('Topic properties updated');Publish a message
const publishRes = await client.publishMessage(topicName, {
MessageBody: 'hello topic <"aliyun-mns-nodejs-sdk">',
MessageAttributes: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
});
console.log('Message published:', publishRes.body);List topics
const listRes = await client.listTopic();
console.log('Topics:', listRes.body);Complete topic example
The following example creates a queue as a message endpoint, creates a topic, publishes a message, receives it from the queue, and cleans up all resources:
const MNSClient = require('@alicloud/mns');
async function topicExample() {
// Initialize the client
const client = new MNSClient('<your-account-id>', {
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
endpoint: 'https://<your-account-id>.mns.<region-id>.aliyuncs.com'
});
const queueName = 'test-queue';
const topicName = 'test-topic';
try {
// Create a queue to receive pushed messages
await client.createQueue(queueName);
console.log('Queue created');
// Create a topic
const topicRes = await client.createTopic(topicName, {
MaximumMessageSize: 65536,
LoggingEnabled: false
});
console.log('Topic created:', topicRes);
// Wait for the resources to become available
await new Promise(resolve => setTimeout(resolve, 2000));
// Get topic properties
const attrRes = await client.getTopicAttributes(topicName);
console.log('Topic properties:', attrRes.body);
// Update topic properties
await client.setTopicAttributes(topicName, {
MaximumMessageSize: 32768
});
console.log('Topic properties updated');
// Publish a message
const publishRes = await client.publishMessage(topicName, {
MessageBody: 'hello topic <"aliyun-mns-nodejs-sdk">',
MessageAttributes: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
});
console.log('Message published:', publishRes.body);
// Receive the message from the queue
const receiveRes = await client.receiveMessage(queueName, 30);
console.log('Message received from queue:', receiveRes.body);
// Delete the message
if (receiveRes.body) {
await client.deleteMessage(queueName, receiveRes.body.ReceiptHandle);
console.log('Message deleted');
}
// List topics
const listRes = await client.listTopic();
console.log('Topics:', listRes.body);
// Clean up
await client.deleteQueue(queueName);
console.log('Queue deleted');
} catch (err) {
console.error('Operation failed:', err);
}
}
topicExample();API reference
Queue methods
Method | Description |
| Create a queue with the specified properties |
| Get queue properties |
| Send a single message to a queue |
| Send multiple messages to a queue |
| Receive a message, with optional long polling |
| Receive multiple messages |
| Change the visibility timeout period of a received message |
| Delete a processed message |
| Delete multiple processed messages |
| List all queues |
| Delete a queue |
Topic methods
Method | Description |
| Create a topic |
| Get topic properties |
| Update topic properties |
| Publish a message to a topic |
| List all topics |
Queue creation parameters
Parameter | Type | Description |
| Integer | Delay in seconds before a message becomes visible. Default: |
| Integer | Maximum message size in bytes. Default: |
| Integer | How long messages are retained in seconds. Default: |
| Integer | Visibility timeout period in seconds after a message is received. Default: |
| Integer | Long polling wait time in seconds. Default: |
Message parameters
Parameter | Type | Description |
| String | Message content. Supports special characters. |
| Integer | Delay in seconds before the message becomes visible. |
| Integer | Message priority. Lower values indicate higher priority. |
Topic creation parameters
Parameter | Type | Description |
| Integer | Maximum message size in bytes. Default: |
| Boolean | Whether to enable logging. Default: |
Topic publish parameters
Parameter | Type | Description |
| String | Message content. |
| String | JSON-stringified key-value pairs for message filtering and routing. |
Version history
Version 1.1.0
Release date: November 27, 2025
Custom endpoint configuration.
Independent read and connection timeout settings.
Improved fault handling.