最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

I'm unable to send or receive messages from Azure servicebus in my Next.js application - Stack Overflow

programmeradmin0浏览0评论

I'm trying to use the @azure/service-bus package to interact with a servicebus queue. However when I try to peek, receive or send messages I'm met with the following error: "TypeError: this.container.get_option is not a function".

Firstly I use this action to fetch the queues present in the servicebus which works as intended.

export async function getQueuesForServicebus(
  connectionString: string,
): Promise<QueueDetails[]> {
  try {
    const client = new ServiceBusAdministrationClient(connectionString);
    const queueDetails: QueueDetails[] = [];

    for await (const queue of client.listQueues()) {
      const props = await client.getQueueRuntimeProperties(queue.name);

      queueDetails.push({
        name: queue.name,
        activeMessageCount: props.activeMessageCount,
        deadLetterMessageCount: props.deadLetterMessageCount,
      });
    }

    return queueDetails;
  } catch (error) {
    console.error("Error fetching queues:", error);
    return [];
  }
}

Then when i attempt to fetch the messages from a given queue like this:

export async function getMessagesFromQueue(
  servicebusName: string,
  queueName: string,
): Promise<QueueMessage[]> {
  try {
    // I have logic here to fetch conn string and verify that it's correct

    const sbClient = new ServiceBusClient(servicebus.connection);
    const receiver = sbClient.createReceiver(queueName);

    const messages = await receiver.receiveMessages(5);
    for (const msg of messages) {
      console.log(`Message received: ${msg.body}`);
    }

    return [];
  } catch (err) {
    console.error(`Error fetching messages from queue: ${queueName}`, err);
    return [];
  }
}

When running the above code I get this in then console:

Error fetching messages from queue: voucher-queue TypeError: Error 0: TypeError: this.container.get_option is not a function
    at new Promise (<anonymous>)
    at async getMessagesFromQueue (src/actions/servicebus.ts:91:21)
  89 |     const receiver = sbClient.createReceiver(queueName);
  90 |
> 91 |     const messages = await receiver.receiveMessages(5);
     |                     ^
  92 |     for (const msg of messages) {
  93 |       console.log(`Message received: ${msg.body}`);
  94 |     }

I have also tried to lift all of this out into a new project but I get the same error again.

Edit: Im using Next.js 15.0.1 and @azure/service-bus 7.9.5

I'm trying to use the @azure/service-bus package to interact with a servicebus queue. However when I try to peek, receive or send messages I'm met with the following error: "TypeError: this.container.get_option is not a function".

Firstly I use this action to fetch the queues present in the servicebus which works as intended.

export async function getQueuesForServicebus(
  connectionString: string,
): Promise<QueueDetails[]> {
  try {
    const client = new ServiceBusAdministrationClient(connectionString);
    const queueDetails: QueueDetails[] = [];

    for await (const queue of client.listQueues()) {
      const props = await client.getQueueRuntimeProperties(queue.name);

      queueDetails.push({
        name: queue.name,
        activeMessageCount: props.activeMessageCount,
        deadLetterMessageCount: props.deadLetterMessageCount,
      });
    }

    return queueDetails;
  } catch (error) {
    console.error("Error fetching queues:", error);
    return [];
  }
}

Then when i attempt to fetch the messages from a given queue like this:

export async function getMessagesFromQueue(
  servicebusName: string,
  queueName: string,
): Promise<QueueMessage[]> {
  try {
    // I have logic here to fetch conn string and verify that it's correct

    const sbClient = new ServiceBusClient(servicebus.connection);
    const receiver = sbClient.createReceiver(queueName);

    const messages = await receiver.receiveMessages(5);
    for (const msg of messages) {
      console.log(`Message received: ${msg.body}`);
    }

    return [];
  } catch (err) {
    console.error(`Error fetching messages from queue: ${queueName}`, err);
    return [];
  }
}

When running the above code I get this in then console:

Error fetching messages from queue: voucher-queue TypeError: Error 0: TypeError: this.container.get_option is not a function
    at new Promise (<anonymous>)
    at async getMessagesFromQueue (src/actions/servicebus.ts:91:21)
  89 |     const receiver = sbClient.createReceiver(queueName);
  90 |
> 91 |     const messages = await receiver.receiveMessages(5);
     |                     ^
  92 |     for (const msg of messages) {
  93 |       console.log(`Message received: ${msg.body}`);
  94 |     }

I have also tried to lift all of this out into a new project but I get the same error again.

Edit: Im using Next.js 15.0.1 and @azure/service-bus 7.9.5

Share Improve this question edited Feb 5 at 7:14 Sampath 3,9692 gold badges6 silver badges24 bronze badges Recognized by Microsoft Azure Collective asked Jan 29 at 7:00 Joel MagnussonJoel Magnusson 112 bronze badges 1
  • use api to send or receive messages from Azure servicebus in my Next.js – Sampath Commented Jan 29 at 10:37
Add a comment  | 

2 Answers 2

Reset to default 0

The error TypeError: this.container.get_option is not a function indicates that the ServiceBusClient is not being properly initialized. This error can occur due to incorrect handling of async operations related to message fetching.

To resolve this, use API Routes in Next.js and call the API in index.tsx. Refer to this documentation for more information on using API routes with middleware.

npx create-next-app --example api-routes-middleware api-routes-middleware-app

Below sample Next.js API code that lists queues, sends a message, and fetches messages.

pages/api/servicebus.ts:

import { ServiceBusClient, ServiceBusAdministrationClient } from "@azure/service-bus";
import type { NextApiRequest, NextApiResponse } from "next";

const connectionString = process.env.AZURE_SERVICE_BUS_CONNECTION_STRING as string;
const queueName = process.env.AZURE_SERVICE_BUS_QUEUE_NAME as string;

if (!connectionString || !queueName) {
  throw new Error("Azure Service Bus connection details are missing");
}

async function getQueues() {
  const client = new ServiceBusAdministrationClient(connectionString);
  const queueDetails: { name: string; activeMessages: number; deadLetters: number }[] = [];

  for await (const queue of client.listQueues()) {
    const props = await client.getQueueRuntimeProperties(queue.name);
    queueDetails.push({
      name: queue.name,
      activeMessages: props.activeMessageCount,
      deadLetters: props.deadLetterMessageCount,
    });
  }
  return queueDetails;
}

async function sendMessage(body: string) {
  const sbClient = new ServiceBusClient(connectionString);
  const sender = sbClient.createSender(queueName);
  await sender.sendMessages({ body });
  await sender.close();
}

async function receiveMessages() {
  const sbClient = new ServiceBusClient(connectionString);
  const receiver = sbClient.createReceiver(queueName, { receiveMode: "peekLock" });
  const messages = await receiver.receiveMessages(5);
  
  await receiver.close();
  return messages.map((msg) => ({ body: msg.body, id: msg.messageId }));
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    switch (req.method) {
      case "GET":
        const messages = await receiveMessages();
        return res.status(200).json(messages);

      case "POST":
        const { message } = req.body;
        if (!message) return res.status(400).json({ error: "Message content required" });

        await sendMessage(message);
        return res.status(200).json({ success: true });

      case "PUT":
        const queues = await getQueues();
        return res.status(200).json(queues);

      default:
        return res.status(405).json({ error: "Method not allowed" });
    }
  } catch (error) {
    console.error("Service Bus Error:", error);
    return res.status(500).json({ error: "Internal Server Error" });
  }
}

index.tsx:

import { useState } from "react";
import useSWR from "swr";

const fetcher = (url: string) => fetch(url).then((res) => res.json());

export default function Home() {
  const { data: messages, error, mutate } = useSWR("/api/servicebus", fetcher);
  const [newMessage, setNewMessage] = useState("");

  const sendMessage = async () => {
    if (!newMessage.trim()) return;

    await fetch("/api/servicebus", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message: newMessage }),
    });

    setNewMessage("");
    mutate(); 
  };

  if (error) return <div>Error loading messages.</div>;
  if (!messages) return <div>Loading...</div>;

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-xl font-bold mb-4">Azure Service Bus Messages</h1>

      <input
        type="text"
        value={newMessage}
        onChange={(e) => setNewMessage(e.target.value)}
        placeholder="Enter message"
        className="border p-2 rounded mr-2"
      />
      <button
        onClick={sendMessage}
        className="bg-blue-500 text-white px-4 py-2 rounded"
      >
        Send Message
      </button>

      <h2 className="text-lg font-bold mt-4">Received Messages:</h2>
      <ul className="list-disc pl-4">
        {messages.map((msg: any, index: number) => (
          <li key={index}>{msg.body}</li>
        ))}
      </ul>
    </div>
  );
}

Output:

I am also using Azure Service Bus. This is my experience:

  • it works in deployed environment
  • if I am using turbopack with next dev AKA next dev --turbo it will complain about not able to create AMQP client

Hope this helps

发布评论

评论列表(0)

  1. 暂无评论