How to Connect Express app to RabbitMQ
Tags: rabbitmq, express, javascript, node
Published: 2023-09-26 15:38:36

## Introduction
RabbitMQ is an open-source message broker software that facilitates message queuing. It provides a platform for different software components to communicate by sending and receiving messages.
Now let's go through the process of connecting RabbitMQ to our Express App
**Step-1**
Run RabbitMQ on your machine
Easiest way to do this use docker image of rabbitmq and run this docker image.
```sh
docker pull rabbitmq
```
Then run the docker image using this command
```sh
docker run -d -p 15672:15672 -p 5672:5672 --hostname my-rabbitmq --name my-rabbitmq-container rabbitmq:3-management
```

**Step-2**
Create Express app

```js
const express = require('express');

const app = express();
const PORT = 3000;

app.post('/orders', (req, res) => {
    res.send('Order submitted');
});

app.listen(PORT, () => {
    console.log(`Server running on ${PORT}`);
});
```
Test your app using postman

**Step-3**
Now it is time add code to connect to rabbitmq
To rabbitmq we need amqplib npm package install this package in your project

```
npm install amqplib
```
Now add code for connection to rabbitmq in your express app

```js
const amqplib = require('amqplib');
const express = require('express');

const app = express();
const PORT = 9005;
let channel, connection;

async function connect() {
    try {
        const amqpServer = 'amqp://localhost:5672';
        connection = await amqplib.connect(amqpServer);
        channel = await connection.createChannel();
        await channel.assertQueue('order');
    } catch (error) {
        console.log(error);
    }
}

app.post('/orders', (req, res) => {
const data = {message: 'Order placed'};
    channel.sendToQueue('order', Buffer.from(JSON.stringify({ ...data, date: new Date() })));
    res.send('Order submitted');
});

app.get('*', (req, res) => {
    res.status(404).send('Not found');
});

app.listen(PORT, () => {
    connect();
    console.log(`Server running on ${PORT}`);
});


```
To make sure your you are connected to rabbitmq you can check rabbitmq management dashboard
You can access it on 

```sh
http://localhost:15672/
```
login credentials are
Username : guest
Password : guest
Now check connection you will find you are connected 
![Connection tab image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b299s6rdgt0qv6raewqe.png)

Now check queue you will find queue created with the name you have given to your queue in my case order

![Queue tab image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3d8g8krqwz5rg0hvcfpz.png)

Now to check you are receiving the data you are sending to queue and perform operation on that make another project install amqplib
Create a file with name worker.js

Now write the code to connect to rabbitmq and also to receive message sent by our express app from the queue

```js
const amqp = require('amqplib');

const connectToRabbitMQ = async () => {
    try {
        const connection = await amqp.connect('amqp://localhost:5672');
        const channel = await connection.createChannel();
        return channel;
    } catch (error) {
        console.error('Error connecting to RabbitMQ:', error);
    }
};

const receiveMessageFromQueue = async (queueName) => {
    const channel = await connectToRabbitMQ();

    channel.assertQueue(queueName, { durable: true });
    channel.consume(queueName, (message) => {
        const content = message.content.toString();
        //perform operations on the message
        console.log(`Received message: ${content}`);
    });
};

const queueName = 'order'; // Replace with your queue name
receiveMessageFromQueue(queueName);

```
The receiveMessageFromQueue function will process the message sent to queue.

Thank you for taking the time to read. I'm in a continuous process of learning and sharing. If you spot any mistakes in my understanding or have any other insights, please feel free to let me know in the comments section.