npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@spotq-org/rabbitmq-client

v1.0.1

Published

Standardized RabbitMQ message broker client with Dead Letter Queuing (DLQ), ACK/NACK handling, and structured logger support for SpotQ microservices

Readme

RabbitMQ Client (@spotq-org/rabbitmq-client)

Standard RabbitMQ client package for SpotQ microservices.


1. Quick Start

Installation

pnpm add @spotq-org/rabbitmq-client

Initialize & Connect

import { RabbitMQClient } from "@spotq-org/rabbitmq-client";

const rmq = new RabbitMQClient({
  url: process.env.RABBITMQ_URL!, // required
  serviceName: "order-service",   // required
  logger: console,                // optional: pass custom logger (e.g. Winston, Pino, or console)
});

await rmq.connect();

2. Configuration (RabbitMQConfig)

When instantiating new RabbitMQClient(config), config accepts the following options:

| Option | Type | Required? | Default | Description | | :--- | :--- | :--- | :--- | :--- | | url | string | YES | — | AMQP connection URL (e.g. amqp://guest:guest@localhost:5672). Credentials in URL are automatically sanitized in error logs. | | serviceName | string | YES | — | Service name identifier used for structured logs and tracing. | | logger | ILogger | Optional | Default logger | Custom logger implementing info, error, warn, and optional debug (e.g. console, Winston, or Pino). | | prefetchCount | number | Optional | 10 | Number of unacknowledged messages the consumer channel will fetch concurrently. | | dlqOptions | DlqOptions | Optional | { enabled: true, dlqSuffix: ".dlq" } | Global Dead Letter Queue (DLQ) settings. |

Passing a Custom Logger

You can pass standard loggers (such as Winston, Pino, or console) directly via logger:

import { RabbitMQClient, type ILogger } from "@spotq-org/rabbitmq-client";
import winston from "winston";

const customLogger: ILogger = winston.createLogger({
  level: "info",
  transports: [new winston.transports.Console()],
});

const rmq = new RabbitMQClient({
  url: process.env.RABBITMQ_URL!,
  serviceName: "restaurant-service",
  logger: customLogger,
});

3. Core Functions

Publish a Message

Sends an object as a JSON message to a queue. If the queue does not exist, it is created automatically.

Always wrap publishToQueue in a try...catch block so your application can handle network disconnects, channel unavailability, or serialization errors gracefully:

try {
  await rmq.publishToQueue("order_created", {
    orderId: "ord_101",
    amount: 450,
  });
  console.log("Message published successfully");
} catch (error) {
  console.error("Failed to publish message:", error);
  // Handle failure (e.g., return HTTP 500, alert, or save to fallback store)
}

Consume Messages

Listens to a queue and runs your handler function whenever a new message arrives.

const handleOrderCreated = async (message: unknown) => {
  console.log("Received order:", message);
};

await rmq.consumeFromQueue("order_created", handleOrderCreated);

Other Helper Functions

  • rmq.isConnected(): Returns true if both the connection and channel are active.

    if (rmq.isConnected()) {
      console.log("Ready to send messages");
    }
  • rmq.getChannel(): Returns the underlying amqplib channel if you need raw channel operations.

    const channel = rmq.getChannel();
  • rmq.close(): Gracefully closes the channel and connection (useful during service shutdown).

    process.on("SIGTERM", async () => {
      await rmq.close();
    });

4. Advanced Options

Both publishToQueue and consumeFromQueue accept optional settings as a third argument:

publishToQueue Options

await rmq.publishToQueue("order_created", message, {
  persistent: true,                       // Save message to disk (default: true)
  headers: { "x-correlation-id": "123" }, // Attach metadata / trace IDs
});

consumeFromQueue Options

await rmq.consumeFromQueue("order_created", handler, {
  requeueOnFailure: false, // If handler throws, retry in main queue instead of DLQ (default: false)
});

5. Dead Letter Queue (DLQ) & Acknowledgment

Automatic DLQ Configuration

A Dead Letter Queue (<queue_name>.dlq) is configured automatically for every queue. If your consumer function throws an error, the message is automatically moved to the DLQ so no data is lost and your main queue does not get blocked.

Malformed JSON Handling: If an unparseable or corrupted payload enters the queue, it is immediately routed directly to the DLQ (requeue: false), preventing infinite retry loops.

How to Turn Off the DLQ

If you do not want a Dead Letter Queue for a specific queue, pass dlq: { enabled: false }:

await rmq.consumeFromQueue("temp_notifications", handler, {
  dlq: { enabled: false },
});

(You can also disable it globally in new RabbitMQClient({ dlqOptions: { enabled: false } })).

How to Turn On noAck (Auto-Ack)

By default, messages are safely acknowledged only after your handler finishes (noAck: false). If you want RabbitMQ to automatically mark messages as acknowledged the moment they are delivered, set noAck: true:

await rmq.consumeFromQueue("logs_queue", handler, {
  noAck: true,
});