Quickstart: How to use Service Bus topics and subscriptions with Node.js and the azure/service-bus package

In this tutorial, you learn how to write a Node.js program to send messages to a Service Bus topic and receive messages from a Service Bus subscription using the new @azure/service-bus package. This package uses the faster AMQP 1.0 protocol whereas the older azure-sb package used Service Bus REST run-time APIs. The samples are written in JavaScript.

Prerequisites

Note

Use Node Package Manager (NPM) to install the package

To install the npm package for Service Bus, open a command prompt that has npm in its path, change the directory to the folder where you want to have your samples and then run this command.

npm install @azure/service-bus

Send messages to a topic

Interacting with a Service Bus topic starts with instantiating the ServiceBusClient class and using it to instantiate the TopicClient class. Once you have the topic client, you can create a sender and use either send or sendBatch method on it to send messages.

  1. Open your favorite editor, such as Visual Studio Code

  2. Create a file called send.js and paste the below code into it. This code will send 10 messages to your topic.

    const { ServiceBusClient } = require("@azure/service-bus"); 
    
    // Define connection string and related Service Bus entity names here
    const connectionString = "";
    const topicName = ""; 
    
    async function main(){
      const sbClient = ServiceBusClient.createFromConnectionString(connectionString); 
      const topicClient = sbClient.createTopicClient(topicName);
      const sender = topicClient.createSender();
    
        try {
            for (let i = 0; i < 10; i++) {
              const message= {
                body: `Hello world! ${i}`,
                label: `test`,
                userProperties: {
                    myCustomPropertyName: `my custom property value ${i}`
                }
              };
              console.log(`Sending message: ${message.body}`);
              await sender.send(message);
            }
    
            await topicClient.close();
          } finally {
            await sbClient.close();
          }
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. Enter the connection string and name of your topic in the above code.

  4. Then run the command node send.js in a command prompt to execute this file.

Congratulations! You just sent messages to a Service Bus queue.

Messages have some standard properties like label and messageId that you can set when sending. If you want to set any custom properties, use the userProperties, which is a json object that can hold key-value pairs of your custom data.

Service Bus topics support a maximum message size of 256 KB in the Standard tier and 1 MB in the Premium tier. There's no limit on the number of messages held in a topic, but there's a limit on the total size of the messages held by a topic. This topic size is defined at creation time, with an upper limit of 5 GB. For more information about quotas, see Service Bus quotas.

Receive messages from a subscription

Interacting with a Service Bus subscription starts with instantiating the ServiceBusClient class and using it to instantiate the SubscriptionClient class. Once you have the subscription client, you can create a receiver and use either receiveMessages or registerMessageHandler method on it to receive messages.

  1. Open your favorite editor, such as Visual Studio Code

  2. Create a file called recieve.js and paste the below code into it. This code will attempt to receive 10 messages from your subscription. The actual count you receive depends on the number of messages in the subscription and network latency.

    const { ServiceBusClient, ReceiveMode } = require("@azure/service-bus"); 
    
    // Define connection string and related Service Bus entity names here
    const connectionString = "";
    const topicName = ""; 
    const subscriptionName = ""; 
    
    async function main(){
      const sbClient = ServiceBusClient.createFromConnectionString(connectionString); 
      const subscriptionClient = sbClient.createSubscriptionClient(topicName, subscriptionName);
      const receiver = subscriptionClient.createReceiver(ReceiveMode.receiveAndDelete);
    
      try {
        const messages = await receiver.receiveMessages(10);
        console.log("Received messages:");
        console.log(messages.map(message => message.body));
    
        await subscriptionClient.close();
      } finally {
        await sbClient.close();
      }
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. Enter the connection string and names of your topic and subscription in the above code.

  4. Then run the command node receiveMessages.js in a command prompt to execute this file.

Congratulations! You just received messages from a Service Bus subscription.

The createReceiver method takes in a ReceiveMode which is an enum with values ReceiveAndDelete and PeekLock. Remember to settle your messages if you use the PeekLock mode by using any of complete(), abandon(), defer(), or deadletter() methods on the message.

Subscription filters and actions

Service Bus supports filters and actions on subscriptions, which allows you to filter the incoming messages to a subscription and to edit their properties.

Once you have an instance of a SubscriptionClient you can use the below methods on it to get, add and remove rules on the subscription to control the filters and actions.

  • getRules
  • addRule
  • removeRule

Every subscription has a default rule that uses the true filter to allow all incoming messages. When you add a new rule, remember to remove the default filter in order for the filter in your new rule to work. If a subscription has no rules, then it will receive no messages.

Note

You can manage Service Bus resources with Service Bus Explorer. The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. The tool provides advanced features like import/export functionality or the ability to test topic, queues, subscriptions, relay services, notification hubs and events hubs.

Next Steps

To learn more, see the following resources.