# Streamlining Messaging with Platformatic RabbitMQ hooks

Secure and reliable messaging between components is crucial in maintaining communication between the different components in a [microservice](https://microservices.io/) architecture. [RabbitMQ](https://www.rabbitmq.com/) is a popular messaging broker that handles asynchronous messaging in [microservice](https://microservices.io/) applications. With [Platformatic RabbitMQ hook](https://github.com/platformatic/rabbitmq-hooks#readme)s, you can integrate [RabbitMQ](https://www.rabbitmq.com/) into your [Platformatic](https://platformatic.dev/) applications.

In this article, you will learn how to use RabbitMQ, a messaging broker, and integrate it with Platformatic’s [RabbitMQ Hooks Stackable](https://marketplace.platformatic.dev/#/detail/template/afe95e28-d7cc-4bdb-bc51-231735a9f735). You will see how you can simplify and enhance message-driven processes in modern applications, focusing on the seamless integration of the [RabbitMQ Hooks Stackable](https://marketplace.platformatic.dev/#/detail/template/afe95e28-d7cc-4bdb-bc51-231735a9f735).

A complete code version is available on [GitHub](https://github.com/iamfortune/Platformatic-RabbitMQ-Hooks-POC).

## **Prerequisites**

To follow this tutorial, make sure to have the following prerequisites:

* Basic understanding of [Platformatic](https://docs.platformatic.dev/docs/Overview) and JavaScript
    
* [Node.js](https://nodejs.org/en/download) LTS version
    
* [Docker](https://www.docker.com/get-started/) installed on your machine
    

## **What is Platformatic RabbitMQ hooks?**

[Platformatic RabbitMQ hooks](https://github.com/platformatic/rabbitmq-hooks#readme) allow you to wrap [RabbitMQ](https://www.rabbitmq.com/) inside your [Platformatic](https://platformatic.dev/) application and export messages published on an exchange to an HTTP endpoint or publish them to an exchange.

[RabbitMQ hook](https://github.com/platformatic/rabbitmq-hooks#readme) is available as a [stackable template](https://marketplace.platformatic.dev/#/detail/template/afe95e28-d7cc-4bdb-bc51-231735a9f735) within the [stackable marketplace](https://marketplace.platformatic.dev/#/). It is the wrapper for [RabbitMQ](https://www.rabbitmq.com/) and your [Platformatic](https://platformatic.dev/) application.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>What is a Stackable?</strong><em>With </em><a target="_blank" rel="noopener noreferrer nofollow" href="https://platformatic.dev/feature/stackables/" style="pointer-events: none"><em>Stackables</em></a><em>, developers can take their code and configurations, encapsulate them into augmented npm modules, and publish them on their internal npm registry. Stackables templates come fully loaded with everything your team needs, including automatic updates, and allow for the simple layering of your specific configurations. The Stackables Marketplace is a one-stop destination for reusing, composing, and publishing microservices and templates</em></div>
</div>

## **Creating your RabbitMQ hooks application**

To create and run our [RabbitMQ hooks](https://github.com/platformatic/rabbitmq-hooks#readme) application, we need to create a [runtime](https://docs.platformatic.dev/docs/runtime/overview) with two Platformatic applications, one for the RabbitMQ hooks and another service for making your messaging application.

Run the command below and follow the steps:

```plaintext
npx create-platformatic@latest
```

And follow the prompts:

```plaintext
? What kind of project do you want to create? Application
? Where would you like to create your project? platformatic
Using existing configuration
? Which kind of project do you want to create? @platformatic/service
? What is the name of the service? handsome-combat
? Do you want to create another service? yes
? Which kind of project do you want to create? @platformatic/rabbitmq-hooks
? What is the name of the service? hoc-honeysuckle
? Do you want to create another service? no
? Which service should be exposed? handsome-combat
? Do you want to use TypeScript? no
? Do you want to initialize git? no
```

*NOTE: Change the URL and directory name in the command to your application URL and name.*

We created a [Runtime](https://docs.platformatic.dev/docs/runtime/overview) with two Platformatic applications: the [RabbitMQ hooks](https://github.com/platformatic/rabbitmq-hooks) and a Platformatic [service](https://docs.platformatic.dev/docs/service/overview). We also exposed the service application as the [entrypoint](https://docs.platformatic.dev/docs/runtime/configuration#entrypoint) for your runtime, in this case, the `handsome-combat` service application from your prompt.

Now navigate to the .env file in the root of the platformatic application and update the `SERVER_HOSTNAME, RABBITMQ_CONNECTION_URL`, and `RABBITMQ_TARGET_URL_0` as shown:

```plaintext
// rabbit-mq-poc/.env
PLT_HOC_HONEYSUCKLE_RABBITMQ_CONNECTION_URL=amqp://localhost:5672 # RabbitMQ connection URL with PORT connection
```

We specified the platformatic server hostname as your `localhost`, and added the connection `URL` to match your `PORT` for RabbitMQ connection, although this is optional.

## **Starting RabbitMQ with Docker**

Before starting your application, you must start the [RabbitMQ](https://www.rabbitmq.com/) container using [Docker](https://hub.docker.com/_/rabbitmq). To do this in the root of your application, create a new file `docker-compose.yml` and add the configuration:

```yaml
services:
  rabbitmq:
    image: rabbitmq:3
    container_name: 'rabbitmq'
    ports:
        - 5672:5672
        - 15672:15672
```

***Note***\*: You can change your RabbitMQ incoming connection port on the\* `docker-compose.yml`*file, but remember to append it to the*`RABBITMQ_CONNECTION_URL`*in your*`.env`*file.*

Start your RabbitMQ with docker using the command:

```plaintext
docker compose up
```

## **Creating a client for the RabbitMQ application server**

Your application is a [Platformatic runtime](https://docs.platformatic.dev/docs/runtime/overview) with two services: the RabbitMQ hooks stackable and your service application. To create a [client](https://docs.platformatic.dev/docs/client/overview#generating-a-client-for-a-service-running-within-platformatic-runtime) to invoke the RabbitMQ hooks from the service application, run the command:

```plaintext
npx platformatic client --runtime hoc-honeysuckle --name rabbit
```

This will create a rabbit folder in the `handsome-combat` application directory with three files:

* `package.json`: This file contains a JSON object of the name and type of your client
    
* `rabbit.d.ts`: This file contains the types and interfaces for your RabbitMQ hooks stackable, including the routes and endpoints from the RabbitMQ hooks.
    
* `rabbit.openapi.json`: A JSON object of your client, including the RabbitMQ hooks endpoint.
    

*NOTE: Change the URL and directory name in the command to your application URL and name.*

## **Sending messages to RabbitMQ with Platformatic RabbitMQ hooks**

To send and receive messages to the RabbitMQ server using Platformatic RabbitMQ hooks. You need to define a `POST` endpoint `/send` for sending messages and another for receiving messages. This will be done in the `root.js` file of the routes directory of your service application.

First, reference the client-server `.ts` file in your `root.js` as shown below:

```typescript
/// <reference path="../rabbit/rabbit.d.ts" />
```

Next, update the `root.js` file by adding a POST endpoint:

```javascript
 fastify.post("/send", async function (request, reply) {
    await request.rabbit.publish({
      exchange: "my-exchange",
      routingKey: "my-queue",
      ...request.body,
    });
    return reply.status(201).send({
      status: "Success",
      statusCode: 201,
      message: "Message successfully sent to RabbitMQ server.",
    });
  });
```

The code above defines a `POST` endpoint at /send. When a request is made, the function sends a message to the RabbitMQ server. It uses r`equest.rabbit.publish` from the RabbitMQ hooks to send a message to RabbitMQ, specifying the `exchange` and `routingKey` with the request body in the message.

After successfully publishing the message, the server responds with a `201` status code and a success message.

## **Receiving messages to RabbitMQ with Platformatic RabbitMQ hooks**

Under the `/send` route, add a new Fastify route called `/receive`.

```javascript
fastify.post("/receive", async function (request, reply) {
    request.log.info({ body: request.body });
    return reply.send({
      status: "Success",
      statusCode: 200,
      message: "Message successfully received from RabbitMQ server.",
    });
  });
```

In the `receive` route, the `request.log.info` receives and logs all incoming messages from the RabbitMQ server and sends a status code of `200` status code and a JSON that says that the message was successfully received from the RabbitMQ server.

Start your server by running:

```plaintext
npm start
```

Open your application URL `http://127.0.0.1:3042`

![](https://lh7-us.googleusercontent.com/_aAcgHL9YL893n4QovVKeES5x0PMUeerGLhg6OSoaROgVdrzxLx4TtURUmldDhBctKp2QhnfJelIeDNsTm_rGGF5xG26UxgUuWus3e5AzZeOhrE2M4Ka0xn1n3zVnexJU7wM6JKOMN5LVp3TWSVR6l8 align="left")

Click on the OpenAPI Documentation button and send a message as shown below:

![](https://lh7-us.googleusercontent.com/ibpgz5Ulk-nbS1fP0dCxoF9M8EudjnmGjHxgIBJwLJ2K6yrOcBBNsIoZ3aRfpcDDEc2BDZGxHUMkgnstIPmPnYZOMa1jdswdlAIioY3ILRZUxeAhzX8yskrkx1hz-ziEVP68Da4tMoqcd_i6-FV3pvM align="left")

You can check your console to see the message received:

![](https://lh7-us.googleusercontent.com/WXfV_A6ykVvzmJalFrQieFNrcRpPlhMhNk0k8Dit6-JXtap9YmPqODocfIZ5i64CR5YgqSNKq1oVA4f67cUeaU7O4yracckj7Y-a6b6eThIIiYHiZnBLrH_uWQPusLDG2Ulnriq0ld2b9vQKCX1Ws8A align="left")

## **Wrapping Up**

Integrating [RabbitMQ](https://www.rabbitmq.com/) with Platformatic using the [RabbitMQ hooks](https://github.com/platformatic/rabbitmq-hooks) offers a seamless solution for handling messages in Platformatic applications.

In this tutorial, we went over the step-by-step process of setting up RabbitMQ hooks in a Platformatic application, configuring Docker for RabbitMQ, creating a client-server with a [Platformatic client](https://docs.platformatic.dev/docs/client/overview#generating-a-client-for-a-service-running-within-platformatic-runtime), and creating endpoints for sending and receiving messages from RabbitMQ.

You can extend this application by creating another service that receives messages from the server.

## **Further resources:**

* [Platformatic documentation](https://docs.platformatic.dev/)
    
* [Platformatic RabbitMQ hooks](https://github.com/platformatic/rabbitmq-hooks)
    
* [Platformatic Runtime documentation](https://docs.platformatic.dev/docs/runtime/overview)
    
* [Platformatic Service documentation](https://docs.platformatic.dev/docs/service/overview)
    
* [Platformatic Client documentation](https://docs.platformatic.dev/docs/client/overview)
