AMQP 0-9-1 Client for Node.js
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.
Common errors
-
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.fixEnsure 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`). -
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`).fixSwitch 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: 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.fixImplement 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: 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.fixVerify 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+).
Warnings
- 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.
- 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.
- 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.
- 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`.
Install
-
npm install amqplib -
yarn add amqplib -
pnpm add amqplib
Imports
- connect
const amqplib = require('amqplib');import { connect } from 'amqplib'; - callback_api connect
const amqpCallback = require('amqplib/callback_api');import { connect as connectCallback } from 'amqplib/callback_api'; - Types
import { Channel, Connection, ConsumeMessage } from 'amqplib';import type { Channel, Connection, ConsumeMessage } from 'amqplib';
Quickstart
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);
}
})();