Azure Service Bus SDK for JavaScript

Connect to Azure Service Bus queues and topics programmatically using the official Azure SDK for JavaScript.

Introduction

The Azure Service Bus SDK for JavaScript provides a robust and efficient way to interact with Azure Service Bus messaging services. This SDK enables you to send and receive messages from queues and topics, manage entities, and leverage advanced features like sessions and dead-letter queues.

Getting Started

To start using the Service Bus SDK, you need to install the necessary package:

npm install @azure/service-bus

You'll also need to obtain a connection string for your Azure Service Bus namespace or use Azure Identity for authentication.

Basic Sender Example

Send a message to a queue:


const { ServiceBusClient } = require("@azure/service-bus");

async function sendMessages() {
    const connectionString = "YOUR_SERVICE_BUS_CONNECTION_STRING";
    const queueName = "YOUR_QUEUE_NAME";
    const sbClient = new ServiceBusClient(connectionString);

    const sender = sbClient.createSender(queueName);

    try {
        await sender.sendMessages({
            body: "Hello, Service Bus!"
        });
        console.log("Sent a message.");
    } finally {
        await sender.close();
        await sbClient.close();
    }
}

sendMessages().catch((err) => {
    console.error("Error sending message: ", err);
});
            

Basic Receiver Example

Receive messages from a queue:


const { ServiceBusClient } = require("@azure/service-bus");

async function receiveMessages() {
    const connectionString = "YOUR_SERVICE_BUS_CONNECTION_STRING";
    const queueName = "YOUR_QUEUE_NAME";
    const sbClient = new ServiceBusClient(connectionString);

    const receiver = sbClient.createReceiver(queueName);

    try {
        const messages = await receiver.receiveMessages(1); // Receive up to 1 message
        if (messages.length === 0) {
            console.log("No messages received.");
            return;
        }

        for (const message of messages) {
            console.log(`Received message: ${message.body}`);
            // Complete the message so it's removed from the queue
            await receiver.completeMessage(message);
            console.log("Completed message.");
        }
    } finally {
        await receiver.close();
        await sbClient.close();
    }
}

receiveMessages().catch((err) => {
    console.error("Error receiving message: ", err);
});
            

Key Concepts

API Reference

ServiceBusClient

The primary client for interacting with Azure Service Bus.

Sender

Used to send messages.

Receiver

Used to receive messages.

Further Reading