# Destination types

> Webhook, RabbitMQ, SQS, Kafka and WebSocket: configuration, a consumer example in Node and Python and how to verify the signature in each one.

Every destination receives the same envelope, with the same signature, the same [filters](/en/webhooks/events/#filters), the same [retries](/en/webhooks/events/#retries-and-failures), the same failure list and the same automatic pause. Only the transport changes.

| Type | When to use it | On by default |
|---|---|---|
| `webhook` | You have an HTTPS URL | yes |
| `rabbitmq` | Your services already consume from an AMQP exchange | no|
| `sqs` | You are on AWS and want a managed queue | no|
| `kafka` | You have a Kafka cluster and want per-connection ordering | no|
| `websocket` | Your process has no public URL (script, desktop, local environment) | no|

A disabled type does not show in the panel, and creating or editing a destination of that type returns `422` [`destination_type_disabled`](/en/errors#destination_type_disabled).

## Create

In the panel, **Event destinations → New destination** and pick the type. Through the API, `POST /v1/destinations` with `type` and a block named after the type:

```bash
curl https://api.messajo.com/v1/destinations \
  -H "Authorization: Bearer $MESSAJO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "label": "Event queue",
    "type": "rabbitmq",
    "rabbitmq": {
      "url": "amqps://messajo:password@mq.yourcompany.com:5671/production",
      "exchange": "messajo",
      "routing_key": "messajo.{type}"
    },
    "event_types": ["message.*"],
    "format": "normalized"
  }'
```

The response carries the signing secret (`whsec_…`) only once, as with webhooks. Passwords and keys in the block never come back: the response shows only the last 4 characters. `POST /v1/destinations/{id}/test` works for every type.

In `routing_key` (RabbitMQ), `message_group_id` (SQS) and `key` (Kafka) you can use the placeholders `{type}`, `{family}`, `{connection}`, `{channel}` and `{org}`; everything else is literal text.

## Global or per connection

Every destination belongs to one connection or is **global** (organization-wide). The `connection_id` field decides: an id makes it that connection's destination; `null` makes it global.

- **Per connection**: receives only that connection's events. Create it in the connection's panel, under **Destinations**.
- **Global**: the organization's webhook. It receives events with no connection (`org.standing_changed`), the connection lifecycle (`connection.*`) and any event from any connection that `event_types` accepts. Only organization keys and members with access to every connection can create or see it. The receiver tells connections apart by the envelope's `connection` field. A global destination matches once per event.

Two example filters:

```json
{ "connection_id": null, "event_types": ["connection.*", "org.*"] }
```

Global with only organization events: connection lifecycle and account standing.

```json
{ "connection_id": null, "event_types": ["*"] }
```

Global with every event from every connection.

`connection_ids` (a list) is a **deprecated** alias of `connection_id`: it accepts `null` or a single id (`[]` is rejected too). More than one id returns `400` `validation_failed`; create one destination per connection. The response carries both fields.

## Signature on every type

The body is the same JSON envelope as the webhook, and the `Messajo-*` headers travel as **message headers** (headers in RabbitMQ and Kafka, `MessageAttributes` in SQS). Verify `Messajo-Signature` over the raw body, exactly like the webhook: see [Verify the signature](/en/webhooks/verify-signature/). In the examples below, `verify` is the function from that page (Python) and `verifyWebhookSignature` comes from the [SDK](/en/sdk/typescript/) (Node).

Delivery is **at least once**: deduplicate by `Messajo-Event-Id`.

## RabbitMQ

| Field | Default | What it is |
|---|---|---|
| `url` | — | `amqps://user:password@host:5671/vhost` |
| `exchange` | — | an exchange that already exists on your server |
| `routing_key` | `messajo.{type}` | routing key |
| `persistent` | `true` | message written to disk on the broker |

Messajo publishes on a confirm channel and waits up to 10 seconds for the broker's `ack`. A `nack` or a timeout counts as a failure and goes into the retries. Each message carries `messageId` = event id and `type` = event type.

```ts title="Node (amqplib)"
import amqp from "amqplib";
import { verifyWebhookSignature } from "@messajo/sdk";

const connection = await amqp.connect(process.env.AMQP_URL!);
const channel = await connection.createChannel();
const { queue } = await channel.assertQueue("messajo-events", { durable: true });
await channel.bindQueue(queue, "messajo", "messajo.message.*");

await channel.consume(queue, async (msg) => {
  if (!msg) return;
  const body = msg.content.toString("utf8");
  const header = String(msg.properties.headers?.["Messajo-Signature"] ?? "");
  const check = await verifyWebhookSignature({ header, body, secret: process.env.MESSAJO_SECRET! });
  if (!check.ok) return channel.nack(msg, false, false);
  const event = JSON.parse(body);
  // handle event.type / event.data
  channel.ack(msg);
});
```

```python title="Python (pika)"
import json
import os

import pika

from verify import verify  # the function from "Verify the signature"

connection = pika.BlockingConnection(pika.URLParameters(os.environ["AMQP_URL"]))
channel = connection.channel()
channel.queue_declare("messajo-events", durable=True)
channel.queue_bind("messajo-events", "messajo", "messajo.message.*")


def handle(ch, method, properties, body: bytes) -> None:
    header = (properties.headers or {}).get("Messajo-Signature", "")
    if not verify(header, body, os.environ["MESSAJO_SECRET"]):
        ch.basic_nack(method.delivery_tag, requeue=False)
        return
    event = json.loads(body)
    # handle event["type"] / event["data"]
    ch.basic_ack(method.delivery_tag)


channel.basic_consume("messajo-events", handle)
channel.start_consuming()
```

## Amazon SQS

| Field | Default | What it is |
|---|---|---|
| `queue_url` | — | `https://sqs.<region>.amazonaws.com/<account>/<queue>` |
| `region` | — | the queue's region |
| `access_key_id` · `secret_access_key` · `session_token` | — | an IAM credential with only `sqs:SendMessage` on that queue |
| `message_group_id` | `{connection}` | `.fifo` queues only: ordering per connection |

On a `.fifo` queue, the `MessageDeduplicationId` is the delivery id. The `Messajo-*` headers go in `MessageAttributes`. SQS accepts up to 1 MiB per message: a larger event fails without retries with `payload_too_large` (it shows in the failure list).

```ts title="Node (@aws-sdk/client-sqs)"
import { DeleteMessageCommand, ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
import { verifyWebhookSignature } from "@messajo/sdk";

const sqs = new SQSClient({});
const QueueUrl = process.env.QUEUE_URL!;

for (;;) {
  const { Messages = [] } = await sqs.send(
    new ReceiveMessageCommand({ QueueUrl, MessageAttributeNames: ["All"], WaitTimeSeconds: 20 })
  );
  for (const msg of Messages) {
    const header = msg.MessageAttributes?.["Messajo-Signature"]?.StringValue ?? null;
    const check = await verifyWebhookSignature({ header, body: msg.Body!, secret: process.env.MESSAJO_SECRET! });
    if (check.ok) {
      const event = JSON.parse(msg.Body!);
      // handle event.type / event.data
    }
    await sqs.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle: msg.ReceiptHandle }));
  }
}
```

```python title="Python (boto3)"
import json
import os

import boto3

from verify import verify

sqs = boto3.client("sqs")
queue_url = os.environ["QUEUE_URL"]

while True:
    response = sqs.receive_message(
        QueueUrl=queue_url, MessageAttributeNames=["All"], WaitTimeSeconds=20
    )
    for msg in response.get("Messages", []):
        attributes = msg.get("MessageAttributes", {})
        header = attributes.get("Messajo-Signature", {}).get("StringValue", "")
        if verify(header, msg["Body"].encode(), os.environ["MESSAJO_SECRET"]):
            event = json.loads(msg["Body"])
            # handle event["type"] / event["data"]
        sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"])
```

## Kafka

| Field | Default | What it is |
|---|---|---|
| `brokers` | — | up to 10, `host:port` |
| `topic` | — | a topic that already exists |
| `ssl` | `true` | TLS |
| `sasl` | `null` | `{ mechanism: "plain" \| "scram-sha-256" \| "scram-sha-512", username, password }` |
| `key` | `{connection}` | message key: same key, same partition, same order |
| `client_id` | `messajo` | client id on the cluster |

The producer is idempotent and waits for all replicas (`acks: -1`), with a 10-second limit. The `Messajo-*` headers go in the message headers.

```ts title="Node (kafkajs)"
import { Kafka } from "kafkajs";
import { verifyWebhookSignature } from "@messajo/sdk";

const kafka = new Kafka({ brokers: process.env.KAFKA_BROKERS!.split(","), ssl: true });
const consumer = kafka.consumer({ groupId: "messajo-events" });
await consumer.connect();
await consumer.subscribe({ topic: "messajo" });

await consumer.run({
  eachMessage: async ({ message }) => {
    const body = message.value?.toString("utf8") ?? "";
    const header = message.headers?.["Messajo-Signature"]?.toString() ?? null;
    const check = await verifyWebhookSignature({ header, body, secret: process.env.MESSAJO_SECRET! });
    if (!check.ok) return;
    const event = JSON.parse(body);
    // handle event.type / event.data
  },
});
```

```python title="Python (confluent-kafka)"
import json
import os

from confluent_kafka import Consumer

from verify import verify

consumer = Consumer({
    "bootstrap.servers": os.environ["KAFKA_BROKERS"],
    "security.protocol": "SSL",
    "group.id": "messajo-events",
})
consumer.subscribe(["messajo"])

while True:
    msg = consumer.poll(1.0)
    if msg is None or msg.error():
        continue
    headers = dict(msg.headers() or [])
    header = headers.get("Messajo-Signature", b"").decode()
    if verify(header, msg.value(), os.environ["MESSAJO_SECRET"]):
        event = json.loads(msg.value())
        # handle event["type"] / event["data"]
```

## WebSocket

Your process opens the connection and Messajo pushes events through it. No public URL or open port needed. The `websocket` destination has no configuration: create it with `"type": "websocket"`.

### Connect

1. Request a ticket with a `read` key: `POST /v1/destinations/{id}/ws-tickets` returns `{ ticket, url, expires_at }`. The ticket is valid for 60 seconds and for a single connection.
2. Open `url` (`wss://api.messajo.com/v1/ws?ticket=wst_…`).
3. Without a ticket, `Authorization: Bearer <read key>` with `?destination_id=dst_…` also works, for clients that send headers on the handshake.

### Protocol

All frames are JSON text.

| Direction | Frame | What to do |
|---|---|---|
| server → you | `{"type":"ready","destination_id","session_id","heartbeat_s":30}` | connected |
| server → you | `{"type":"event","delivery_id","attempt","signature","event":{...}}` | process it and send the `ack` |
| server → you | `{"type":"ping","t"}` | reply `{"type":"pong","t"}` with the same `t` |
| you → server | `{"type":"ack","delivery_id"}` | confirms the delivery |

- **Ack:** without an `ack`, the delivery stays pending and comes back on the next attempt, like a webhook without a `2xx`. The `ack` only counts on a session of the same destination.
- **Signature:** `signature` is the same `Messajo-Signature`, computed over the bytes of `event` exactly as they appear in the frame. The session is already authenticated by the ticket; verifying is optional.
- **Sessions:** up to 5 per destination. All of them receive the events: deduplicate by `event.id`. Order is not guaranteed.
- With no client connected, the delivery fails with `no_client_connected` and goes into the normal retries.

| Close code | Reason |
|---|---|
| `4401` | invalid ticket or key ([`ws_ticket_invalid`](/en/errors#ws_ticket_invalid)) |
| `4403` | the destination is not `websocket` or is not active |
| `4408` | no `pong` for 75 seconds |
| `4410` | the destination was deleted |
| `4429` | there are already 5 sessions ([`ws_session_limit`](/en/errors#ws_session_limit)) |

```ts title="Node (SDK)"
import { Messajo, connectEvents } from "@messajo/sdk";

const messajo = new Messajo({ apiKey: process.env.MESSAJO_API_KEY! });
const socket = connectEvents({
  client: messajo,
  destinationId: "dst_...",
  onEvent: async (event) => {
    // the ack goes out when this resolves; if it throws, Messajo delivers again
    console.log(event.type);
  },
});
await socket.ready;
```

`connectEvents` requests the ticket, answers the `ping`, sends the `ack` and reconnects with increasing waits (1 s up to 30 s). On Node 20, pass the `WebSocket` option (from the `ws` package).

```python title="Python (websockets)"
import asyncio
import json
import os

import requests
import websockets

API = "https://api.messajo.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['MESSAJO_API_KEY']}"}


async def main(destination_id: str) -> None:
    while True:
        ticket = requests.post(
            f"{API}/destinations/{destination_id}/ws-tickets", headers=HEADERS, timeout=10
        ).json()
        async with websockets.connect(ticket["url"]) as ws:
            async for raw in ws:
                frame = json.loads(raw)
                if frame["type"] == "ping":
                    await ws.send(json.dumps({"type": "pong", "t": frame["t"]}))
                elif frame["type"] == "event":
                    event = frame["event"]
                    # handle event["type"] / event["data"]
                    await ws.send(json.dumps({"type": "ack", "delivery_id": frame["delivery_id"]}))
        await asyncio.sleep(1)


asyncio.run(main("dst_..."))
```
