---
name: amqplib-8a006e90adee
description: >-
  amqplib is the Node.js client library for RabbitMQ and other AMQP 0-9-1
  brokers. Use it to publish and consume messages from JavaScript or
  TypeScript: work queues, topic exchanges, dead-letter queues, publisher
  confirms, manual acknowledgments, prefetch limits and automatic reconnection.
  Use when someone asks to "connect Node.js to RabbitMQ", "send messages to a
  queue from Node", "consume RabbitMQ messages in TypeScript", "retry failed
  jobs with a dead-letter queue" or "reconnect amqplib after the broker
  restarts". Covers amqplib 2.x.
license: Apache-2.0
compatibility: "Node.js 18+, amqplib 2.2 (TypeScript types are bundled), a RabbitMQ 4.x broker or any AMQP 0-9-1 server."
metadata:
  author: terminal-skills
  version: "1.1.0"
  category: development
  tags: "rabbitmq, amqp, messaging, nodejs, queues"
  repository: https://github.com/amqp-node/amqplib
---

# amqplib

## Overview

amqplib speaks AMQP 0-9-1 from Node.js. It is only the client: the broker, exchange types, policies, clustering and operations are covered by the `rabbitmq` skill. This skill is about the Node API and its pitfalls.

Version 2.x (2.2.0 in September 2026) keeps the 0.x/1.x API. What changed since the old tutorials:

- **Types are bundled** (since 1.2.0). Do not install `@types/amqplib`; the DefinitelyTyped package stopped at 0.10.x.
- **Node.js 18 or newer** (since 1.0.0), and 0.10.6 or later is required for RabbitMQ 4.1+ (frame size).
- **Connection recovery is built in** (since 1.1.0): pass `recovery` to `connect` and the connection reconnects with backoff.
- **`heartbeat: 0` now disables heartbeats** (2.0.0). Before, it meant "use the server's value". Omit the option for the server default.
- The promise API is the default import (`amqplib`); the callback API lives in `amqplib/callback_api`.

## Instructions

### Install

```bash
npm install amqplib
docker run -d --name rabbit -p 127.0.0.1:5672:5672 -p 127.0.0.1:15672:15672 rabbitmq:4-management
```

Management UI: http://localhost:15672. Keep the broker URL in an environment variable such as `RABBITMQ_URL` (`amqp://orders_app:<password>@localhost:5672/shop`, TLS: `amqps://`). Do not use the default `guest` account outside the machine running the broker.

### Connect once, open channels

A connection is one TCP socket; keep one per process. A channel is a lightweight session on it. Use one channel for publishing and a separate one for consuming, because a consumer that is blocked by `prefetch` should not stall publishes.

```typescript
import amqp, { type ChannelModel, type ConsumeMessage } from "amqplib";

const connection = await amqp.connect(process.env.RABBITMQ_URL!);
connection.on("error", (err) => console.error("connection error", err.message));
connection.on("close", () => console.error("connection closed"));
```

A channel closes on any channel-level error (publishing to a missing exchange, acking twice, redeclaring a queue with different arguments). Attach `channel.on("error", ...)` and `channel.on("close", ...)` and open a new channel when it happens.

### Declare topology with a dead-letter queue

```typescript
const ch = await connection.createChannel();
await ch.assertExchange("orders.dlx", "fanout", { durable: true });
await ch.assertQueue("orders.failed", { durable: true });
await ch.bindQueue("orders.failed", "orders.dlx", "");
await ch.assertQueue("orders", {
  durable: true,
  arguments: { "x-dead-letter-exchange": "orders.dlx", "x-message-ttl": 86_400_000 },
});
```

`assertQueue` fails (and closes the channel) if the queue exists with different arguments. Change arguments by creating a new queue name or by using a RabbitMQ policy.

### Publish with confirms

A plain channel's `sendToQueue` returns before the broker has the message. Use a confirm channel when losing a message matters:

```typescript
const pub = await connection.createConfirmChannel();

async function publishOrder(order: { orderId: string; totalCents: number }) {
  const ok = pub.sendToQueue("orders", Buffer.from(JSON.stringify(order)), {
    persistent: true,                 // written to disk; the queue must be durable too
    contentType: "application/json",
    messageId: order.orderId,
  });
  if (!ok) await new Promise((resolve) => pub.once("drain", resolve)); // write buffer is full
  await pub.waitForConfirms();        // rejects if the broker nacks any outstanding publish
}
```

`publish(exchange, routingKey, content, options)` is the exchange variant. A message published to an exchange with no matching queue is dropped silently unless you set `mandatory: true` and listen to the channel's `return` event.

### Consume with manual acknowledgment

```typescript
const sub = await connection.createChannel();
await sub.prefetch(10);               // at most 10 unacknowledged messages per consumer

await sub.consume("orders", async (msg) => {
  if (msg === null) return;           // the broker cancelled the consumer (queue deleted, node down)
  try {
    await handleOrder(JSON.parse(msg.content.toString()));
    sub.ack(msg);
  } catch (err) {
    // requeue once, then dead-letter; msg.fields.redelivered tells which attempt this is
    sub.nack(msg, false, !msg.fields.redelivered);
  }
});
```

Never pass `noAck: true` for work that must not be lost. Ack and nack each message exactly once, on the channel that delivered it. An unhandled exception inside the callback leaves the message unacknowledged until the channel closes.

### Reconnect automatically

```typescript
const conn = await amqp.connect(process.env.RABBITMQ_URL!, {
  recovery: {
    initialDelay: 200,                // ms
    maxDelay: 30_000,
    maxRetries: Infinity,
    initialMaxRetries: 5,             // fail fast if the broker is down at startup
    async setup(model: ChannelModel) {   // runs after every (re)connect; the annotation is needed for TypeScript
      const ch = await model.createChannel();
      await ch.prefetch(10);
      await ch.assertQueue("orders", {   // same arguments as the first declaration, or the broker answers 406
        durable: true,
        arguments: { "x-dead-letter-exchange": "orders.dlx", "x-message-ttl": 86_400_000 },
      });
      await ch.consume("orders", (msg: ConsumeMessage | null) => { if (msg) ch.ack(msg); });
    },
  },
});
conn.on("disconnect", (err) => console.warn("lost broker:", err.message));
conn.on("reconnect-scheduled", ({ attempt, delay }) => console.log(`retry ${attempt} in ${delay} ms`));
conn.on("reconnect-failed", (err) => { console.error(err); process.exit(1); });
```

Recovery re-establishes the connection only. Channels, queues, bindings and consumers created before the drop are gone, so put every declaration and `consume` call in `setup`. Options: `waitForConnect: false` returns the handle immediately (await `conn.waitForConnect()` later), `calculateDelay(attempt)` replaces the built-in backoff (2.2.0; your function must enforce its own cap).

## Examples

### Example 1: Send order jobs to a worker

**Request:** "Our checkout service in Node should hand off confirmation emails to a worker, and nothing may be lost if the worker restarts."

Producer in `checkout.ts`, using the confirm channel from above:

```typescript
await publishOrder({ orderId: "ORD-20481", totalCents: 12990 });
```

Worker in `mail-worker.ts`: the consumer from the previous section with `handleOrder` sending the email. Start it, then run `docker exec rabbit rabbitmqctl list_queues name messages_ready messages_unacknowledged`:

```
orders    0    0
```

Stop the worker, publish three more orders, and the same command shows `orders  3  0`. Restart the worker and it drains them; a message whose handler throws twice lands in `orders.failed`.

### Example 2: Topic events for several services

**Request:** "Billing wants every order.* event, analytics wants everything."

```typescript
const ch = await connection.createChannel();
await ch.assertExchange("events", "topic", { durable: true });

async function subscribe(queueName: string, pattern: string, onEvent: (key: string, body: unknown) => Promise<void>) {
  await ch.assertQueue(queueName, { durable: true });   // named and durable: events wait while the service is down
  await ch.bindQueue(queueName, "events", pattern);
  await ch.consume(queueName, async (msg) => {
    if (!msg) return;
    await onEvent(msg.fields.routingKey, JSON.parse(msg.content.toString()));
    ch.ack(msg);
  });
}

await subscribe("billing.orders", "order.*", async (key, body) => console.log(key, body));
await subscribe("analytics.all", "#", async (key, body) => console.log(key, body));

ch.publish("events", "order.created", Buffer.from(JSON.stringify({ orderId: "ORD-20482", items: 3 })), { persistent: true });
```

Both queues get `order.created`; a later `user.signup` reaches only `analytics.all`.

## Guidelines

- Messages are `Buffer`s. Serialize and parse yourself, and set `contentType` so other consumers know the format.
- Durable queue plus `persistent: true` are both needed to survive a broker restart. Persistence alone is not delivery: use a confirm channel.
- Delivery is at least once. Make handlers idempotent, for example by recording `messageId`.
- Exclusive, auto-delete queues (`assertQueue("", { exclusive: true })`) vanish with the connection; use them only for throwaway subscribers.
- Do not open a connection per message. Do not share one channel between publishers and long-running consumers.
- On shutdown call `await channel.close()` then `await connection.close()` so in-flight acks are sent.
- Quorum queues (`arguments: { "x-queue-type": "quorum" }`) are the recommended replicated type on RabbitMQ 4; classic mirrored queues are gone.
- Broker setup, policies, retries with delay exchanges and monitoring belong to the `rabbitmq` skill.


---
Source attribution: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/amqplib/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Dave AI.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2025 Terminal Skills

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Dave AI resource metadata

Creator / publisher: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/amqplib/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, DevOps / SRE, Data Engineer
Specialties: Backend, API
Tools: Rabbitmq
Country applicability: Country not specified
Classification basis: Source category, role and specialization labels
Instruction SHA-256: 92bb4f844ae20bbe79fd5cb2fde4f81f4d852b00c3ef971d18c0479b6cad654a
