reactjsazureazureservicebus

How to send/receive messages using Azure Service Bus Topic/Queue from Browser(React JS) in React app using npm create-react-app my-app


I am able to send/receive messages in Azure Service Bus from the browser (React JS) in a React app created using the below command: npm create vite@latest my-app--template react with the react version of 18.3.1. The configuration is the addition of nodePolyfills in vite.config.js, the installation of process, util, stream-browserify, path buffer, and os-browserify, and the configuration of these packages in config-corrides.jsx. Using this configuration, I resolved the webpack error and was successfully able to send messages to the topic/queue. And I have used this package with the version "@azure/service-bus":^7.9.5".

Now I want to send/receive messages using Azure Service Bus from the browser in a React app created using this command: npm create-react-app my-app with React version 16.13.1. I tried to use this "@azure/service-bus" package with this version "^7.5.0" because here I don't need to do webpack configuration and also am not getting any error like "process is not defined," but I am not able to send messages to Azure Service Bus. So I wanted to know what type of configuration I need to use the Node.js "@azure/service-bus" library compatible with the browser and to send/receive messages to Azure Service Bus like I have done in the Vite + React app. It will be helpful if you are able to share some code snippets along with configurations done for using the Azure Service Bus library, which works with the browser, so that I get a head start.


Solution

  • I tried the following ReactJS project to send and receive messages to/from the Azure Service Bus Queue and Topic in the browser.

    Here is the complete GitHub repository.

    AzureServiceBusComponent.js :

    import React, { useState } from 'react';
    import { ServiceBusClient } from '@azure/service-bus';
    import { setLogLevel } from '@azure/logger';
    
    setLogLevel('verbose');
    
    const safeTrim = (value) => (value || '').trim();
    const queueConnectionString = safeTrim(process.env.REACT_APP_QUEUE_CONNECTION_STRING);
    const topicConnectionString = safeTrim(process.env.REACT_APP_TOPIC_CONNECTION_STRING);
    const queueName = safeTrim(process.env.REACT_APP_QUEUE_NAME);
    const topicName = safeTrim(process.env.REACT_APP_TOPIC_NAME);
    const subscriptionName = safeTrim(process.env.REACT_APP_SUBSCRIPTION_NAME);
    const timeOutInMs = Number(process.env.REACT_APP_TIMEOUT_IN_MS) || 60000;
    
    function AzureServiceBusComponent() {
      const [responseMessage, setResponseMessage] = useState('');
      const [receivedQueueMessages, setReceivedQueueMessages] = useState([]);
      const [receivedTopicMessages, setReceivedTopicMessages] = useState([]);
    
      if (!queueConnectionString || !topicConnectionString) {
        console.error("Azure Service Bus connection strings are not defined.");
        return null;
      }
    
      const queueClient = new ServiceBusClient(queueConnectionString, {
        retryOptions: {
          timeoutInMs: timeOutInMs,
        },
      });
      const topicClient = new ServiceBusClient(topicConnectionString, {
        retryOptions: {
          timeoutInMs: timeOutInMs,
        },
      });
    
      const queueSender = queueClient.createSender(queueName);
      const topicSender = topicClient.createSender(topicName);
    
      const sendMessageToQueue = async () => {
        try {
          await queueSender.sendMessages({ body: 'Hello Kamali, sent to Queue!' });
          setResponseMessage('Message sent to queue successfully!');
        } catch (error) {
          console.error('Error sending message to queue:', error);
        }
      };
      const sendMessageToTopic = async () => {
        try {
          await topicSender.sendMessages({ body: 'Hello Kamali, sent to Topic!' });
          setResponseMessage('Message sent to topic successfully!');
        } catch (error) {
          console.error('Error sending message to topic:', error);
        }
      };
    
      const receiveMessagesFromQueue = async () => {
        const receiver = queueClient.createReceiver(queueName, { receiveMode: 'receiveAndDelete' });
        try {
          const messages = await receiver.receiveMessages(5);
          const newMessages = messages.map((msg) => msg.body);
          setReceivedQueueMessages((prev) => [...prev, ...newMessages]);
        } catch (error) {
          console.error('Error receiving messages from queue:', error);
        } finally {
          await receiver.close();
        }
      };
      const receiveMessagesFromTopic = async () => {
        const receiver = topicClient.createReceiver(topicName, subscriptionName, { receiveMode: 'receiveAndDelete' });
        try {
          const messages = await receiver.receiveMessages(5);
          const newMessages = messages.map((msg) => msg.body);
          setReceivedTopicMessages((prev) => [...prev, ...newMessages]);
        } catch (error) {
          console.error('Error receiving messages from topic:', error);
        } finally {
          await receiver.close();
        }
      };
    
      return (
        <div>
          <h2>Azure Service Bus</h2>
          <button onClick={sendMessageToQueue}>Send Message to Queue</button>
          <button onClick={sendMessageToTopic}>Send Message to Topic</button>
          {responseMessage && <p>{responseMessage}</p>}
    
          <div>
            <h3>Received Queue Messages</h3>
            <button onClick={receiveMessagesFromQueue}>Receive Messages from Queue</button>
            <ul>
              {receivedQueueMessages.map((msg, index) => (
                <li key={index}>{msg}</li>
              ))}
            </ul>
          </div>
    
          <div>
            <h3>Received Topic Messages</h3>
            <button onClick={receiveMessagesFromTopic}>Receive Messages from Topic</button>
            <ul>
              {receivedTopicMessages.map((msg, index) => (
                <li key={index}>{msg}</li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    export default AzureServiceBusComponent;
    

    .env :

    REACT_APP_QUEUE_CONNECTION_STRING=<queueconestring>
    REACT_APP_TOPIC_CONNECTION_STRING=<topicconnestring>
    REACT_APP_QUEUE_NAME=<queuename>
    REACT_APP_TOPIC_NAME=<topicname>
    REACT_APP_SUBSCRIPTION_NAME=<subname>
    REACT_APP_TIMEOUT_IN_MS=60000
    

    Output :

    I successfully sent and received messages to and from the Azure Service Bus Queue, as shown below.

    enter image description here

    I got the following message in the Azure Service Bus Queue when I sent it.

    enter image description here

    I successfully sent and received messages to and from the Azure Service Bus Topic, as shown below.

    enter image description here

    I got the following message in the Azure Service Bus Topic when I sent it.

    enter image description here