AMQP 0-9-1 Client for Node.js

raw JSON →
1.0.3 verified Tue Apr 21 auth: no javascript

amqplib is a robust and widely-used library for building AMQP 0-9-1 clients in Node.js, specifically designed for interaction with brokers like RabbitMQ. Currently stable at version 1.0.3, it offers both a traditional callback-based API and a modern Promise/async-await API, catering to diverse asynchronous programming styles. The library generally maintains a consistent release cadence, incorporating updates and compatibility fixes. A key differentiator is its comprehensive implementation of the AMQP 0-9-1 protocol, covering both high-level and low-level functionalities, ensuring full control over message queuing operations. It explicitly does not support AMQP 1.0 or AMQP 0-10, focusing solely on the 0-9-1 specification. It is actively maintained, stable, and used in production environments, with ongoing efforts to improve test coverage and performance. Its minimal dependencies make it a lean choice for AMQP communication.

error Error: connect ECONNREFUSED 127.0.0.1:5672
cause The `amqplib` client could not establish a connection to the RabbitMQ server, likely because the server is not running or is inaccessible at the specified address and port.
fix
Ensure your RabbitMQ server is running and accessible from the machine where your Node.js application is executing. Check the host and port in your connection string (e.g., amqp://localhost:5672).
error ReferenceError: require is not defined
cause You are attempting to use the CommonJS `require` syntax in an ES Module (ESM) context (e.g., a `.mjs` file or a `.js` file in a project with `"type": "module"` in `package.json`).
fix
Switch to ESM import statements (e.g., import { connect } from 'amqplib';) or ensure your file is treated as a CommonJS module (e.g., rename to .cjs or remove "type": "module" from package.json).
error Error: Channel closed
cause An operation was attempted on an AMQP channel that has already been closed, either explicitly by your code or implicitly by an error on the broker side.
fix
Implement proper error handling for channel operations and ensure you are not attempting to reuse a closed channel. Recreate the channel if necessary after it has closed.
error Error: Incompatible protocol version. Client sent 0-9-1, server sent X-Y-Z
cause `amqplib` (0-9-1) is attempting to connect to an AMQP broker that is expecting a different protocol version.
fix
Verify the AMQP protocol version expected by your broker and ensure it is 0-9-1. If using RabbitMQ, check its version compatibility (e.g., amqplib 0.10.7+ for RabbitMQ 4.1.0+).
breaking As of version 1.0.3, `amqplib` officially requires Node.js version 18 or higher due to its `engines` declaration. Older versions (e.g., v0.8.0) dropped support for Node.js < v10, but the current major version has further increased this baseline requirement.
fix Ensure your Node.js environment is version 18 or newer. Update Node.js or use a tool like `nvm` to manage versions.
gotcha For compatibility with RabbitMQ 4.1.0 and later releases, `amqplib` versions 0.10.7 or newer are required. Using older `amqplib` versions with newer RabbitMQ might lead to protocol mismatches or unexpected behavior.
fix Upgrade `amqplib` to version 0.10.7 or newer if you are using RabbitMQ 4.1.0 or a later version.
gotcha `amqplib` strictly adheres to the AMQP 0-9-1 protocol specification. It explicitly does not implement or support AMQP 1.0 or AMQP 0-10. Attempting to connect to brokers expecting these different protocol versions will fail.
fix Verify that your AMQP broker (e.g., RabbitMQ) is configured for AMQP 0-9-1. If you require AMQP 1.0, consider an alternative library that specifically supports that protocol.
gotcha When running tests or connecting to remote/public RabbitMQ instances, network latency or server load can lead to connection timeouts. This is particularly noted with instances like `dev.rabbitmq.com`.
fix Increase connection timeout settings if available, ensure stable network connectivity, or use a local RabbitMQ instance for development and testing to reduce latency.
npm install amqplib
yarn add amqplib
pnpm add amqplib

Demonstrates connecting to RabbitMQ, setting up a queue, and both publishing and consuming messages using the modern Promise/Async API.

import { connect } from 'amqplib';

(async () => {
  const queue = 'tasks';
  let connection;
  try {
    connection = await connect('amqp://localhost');
    const channel = await connection.createChannel();
    await channel.assertQueue(queue, { durable: false });

    // Listener (Consumer)
    channel.consume(queue, (msg) => {
      if (msg !== null) {
        console.log('Received message:', msg.content.toString());
        channel.ack(msg);
      } else {
        console.log('Consumer cancelled by server');
      }
    }, { noAck: false });

    console.log('Waiting for messages in %s. To exit press CTRL+C', queue);

    // Sender (Producer)
    const senderChannel = await connection.createChannel();
    setInterval(() => {
      const message = `Task update: ${new Date().toISOString()}`;
      senderChannel.sendToQueue(queue, Buffer.from(message));
      console.log('Sent:', message);
    }, 2000);

  } catch (error) {
    console.error('Failed to connect to RabbitMQ or perform operations:', error);
    if (connection) {
      await connection.close();
    }
    process.exit(1);
  }
})();