# Inbox and DMs

Build one inbox per customer, written by webhooks and read from your database, with replies and backfills through the inbox API.

import { Tab, Tabs } from 'fumadocs-ui/components/tabs';

By the end of this page, each customer reads and answers their DMs from Instagram, Facebook, X and the other messaging platforms inside your product.

## How the data flows

Webhooks write your inbox database. API calls are for sending and backfill.

Conversations belong to accounts, and accounts live in the customer's profile. So `profileId` scopes an inbox to one customer.

<Mermaid
  chart={`flowchart LR
  subgraph zernio ["Zernio"]
    API["Inbox API"]
    EV["Webhooks"]
  end
  subgraph app ["Your app"]
    BF["Backfill job
once, at onboarding"]
    HOOK["Webhook endpoint"]
    DB[("Your inbox DB")]
    UI["Customer inbox UI"]
  end
  API -->|"conversation history"| BF
  EV -->|"message.received ..."| HOOK
  BF -->|"writes"| DB
  HOOK -->|"writes"| DB
  DB -->|"reads"| UI
  UI -.->|"never: poll for new messages"| API
  linkStyle 5 stroke:#f43f5e,color:#f43f5e,stroke-dasharray:6 4;`}
/>

Polling each of 500 customers' conversations every 30 seconds is 1,000 requests per minute of mostly empty responses. That is above the 600 per minute [rate limit](/guides/rate-limits), with up to 30 seconds of latency.

Webhook-first costs about 0 standing requests and delivers on push.

## Before you start

You need each customer's profile, created with their `externalId` as in the [core model](/multi-tenant), and one webhook endpoint.

## Step 1: Write your inbox from webhooks

Subscribe once to the [inbox events](/webhooks/inbox) and handle each one:

| Event | Fires when | What to update |
|---|---|---|
| [`conversation.started`](/webhooks/inbox/conversation-started) | First message of a new conversation | Create the conversation |
| [`message.received`](/webhooks/inbox/message-received) | An incoming DM arrives | Append the message, bump the unread count |
| [`message.sent`](/webhooks/inbox/message-sent) | A message goes out from the connected account | Append or confirm the message |
| [`message.delivered`](/webhooks/inbox/message-delivered) / [`message.read`](/webhooks/inbox/message-read) | The platform reports receipts | Mark the message row delivered or read |
| [`message.failed`](/webhooks/inbox/message-failed) | A send is rejected | Show the error inline so the customer can retry |

Inbox payloads carry the account, not the profile. A `message.received` delivery:

```json
{
  "id": "evt_5f8e2a1c",
  "event": "message.received",
  "message": {
    "id": "66d4a1b2c3e4f5a6b7c8d9e1",
    "conversationId": "66c3d2ae7b4f6c8d0e1f2a3b",
    "platform": "instagram",
    "direction": "incoming",
    "text": "Hi, is this still available?",
    "sender": { "id": "17841400000000000", "name": "Jane", "username": "jane_doe" }
  },
  "conversation": { "id": "66c3d2ae7b4f6c8d0e1f2a3b", "status": "active" },
  "account": { "id": "66b2e19d8c3f5a7e9d0b1c2d", "accountId": "66b2e19d8c3f5a7e9d0b1c2d", "profileId": "66a1f0c2a4b9d3e8f1a2b3c4", "platform": "instagram" },
  "profiles": [{ "id": "66a1f0c2a4b9d3e8f1a2b3c4", "externalId": "cus_8f3a2" }],
  "timestamp": "2027-01-04T14:00:03Z"
}
```

The customer is `profiles[0].externalId`, the id you set on their profile in the [core model](/multi-tenant#step-1-create-a-profile-per-customer). `account.id` tells you which of their accounts received the message. One endpoint serves every customer.

Delivery is at least once, so dedupe on the event `id`.

Acknowledge within 5 seconds by enqueueing the event and processing it on a worker. A slower handler triggers redeliveries.

`X-Zernio-Signature` is the hex HMAC-SHA256 of the raw body, keyed by your endpoint's secret. Compare it before you parse. The [webhooks overview](/webhooks) covers the secret and the retry schedule.

<Tabs items={['Node.js', 'Python']}>
<Tab value="Node.js">
```typescript
import crypto from 'crypto';

// Your single webhook endpoint, shared by every customer
export const POST = async (req: Request) => {
  const secret = process.env.ZERNIO_WEBHOOK_SECRET;
  if (!secret) return new Response('No secret provided.', { status: 401 });

  const rawBody = await req.text();
  const computedSignature = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');

  if (req.headers.get('X-Zernio-Signature') !== computedSignature) {
    return new Response('Invalid signature', { status: 400 });
  }

  const event = JSON.parse(rawBody);

  if (await alreadyProcessed(event.id)) return Response.json({ ok: true });

  await queue.enqueue(event);
  return Response.json({ ok: true });
};

// Worker, off the request path
async function handleInboxEvent(event) {
  const customer = await customerById(event.profiles[0].externalId);

  switch (event.event) {
    case 'conversation.started':
      return db.createConversation(customer.id, event.conversation);
    case 'message.received':
      return db.appendMessage(customer.id, event.message, { unread: +1 });
    case 'message.sent':
    case 'message.delivered':
    case 'message.read':
      return db.updateMessageStatus(customer.id, event.message);
    case 'message.failed':
      return db.markFailed(customer.id, event.message);
  }
}
```
</Tab>
<Tab value="Python">
```python
import hashlib
import hmac
import json
import os


# Your single webhook endpoint, shared by every customer
@app.post("/webhooks/zernio")
async def zernio_webhook(request: Request):
    raw = await request.body()
    secret = os.environ["ZERNIO_WEBHOOK_SECRET"]
    computed = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(computed, request.headers.get("X-Zernio-Signature", "")):
        return Response("Invalid signature", status_code=400)

    event = json.loads(raw)

    if already_processed(event["id"]):
        return {"ok": True}

    queue.enqueue(event)
    return {"ok": True}


# Worker, off the request path
def handle_inbox_event(event):
    customer = customer_by_id(event["profiles"][0]["externalId"])

    match event["event"]:
        case "conversation.started":
            db.create_conversation(customer.id, event["conversation"])
        case "message.received":
            db.append_message(customer.id, event["message"], unread=1)
        case "message.sent" | "message.delivered" | "message.read":
            db.update_message_status(customer.id, event["message"])
        case "message.failed":
            db.mark_failed(customer.id, event["message"])
```
</Tab>
</Tabs>

<Callout type="info">
WhatsApp conversations run through the same inbox API with extra rules (the 24-hour customer service window, template messages). See [WhatsApp inbox](/platforms/whatsapp/inbox).
</Callout>

## Step 2: Send replies

Call `POST /v1/inbox/conversations/{conversationId}/messages` with `accountId` and `message`.

Send an `Idempotency-Key` header, one UUID per reply. A retry after a lost response then replays the original `200` instead of sending the message twice. The [idempotency guide](/guides/idempotency) has the full rules.

<Callout type="warn">
The Python client's `send_inbox_message` takes no idempotency key, so a retry from Python sends a second message.
</Callout>

A [typing indicator](/messages/send-typing-indicator) while the customer composes and [mark read](/messages/mark-conversation-read) when they open the conversation make the embedded inbox feel native.

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
import { randomUUID } from 'crypto';
import Zernio from '@zernio/node';

const zernio = new Zernio();

const { data: sent } = await zernio.messages.sendInboxMessage({
  path: { conversationId: '66c3d2ae7b4f6c8d0e1f2a3b' },
  headers: { 'Idempotency-Key': randomUUID() },
  body: {
    accountId: '66b2e19d8c3f5a7e9d0b1c2d',
    message: 'Yes, still available. Want me to hold it for you?',
  },
});

console.log(sent.data.messageId);
```
</Tab>
<Tab value="Python">
```python
from zernio import Zernio

client = Zernio()

sent = client.messages.send_inbox_message(
    conversation_id="66c3d2ae7b4f6c8d0e1f2a3b",
    account_id="66b2e19d8c3f5a7e9d0b1c2d",
    message="Yes, still available. Want me to hold it for you?",
)

print(sent["data"]["messageId"])
```
</Tab>
<Tab value="curl">
```bash
curl -X POST "https://zernio.com/api/v1/inbox/conversations/66c3d2ae7b4f6c8d0e1f2a3b/messages" \
  -H "Authorization: Bearer $ZERNIO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 4b4986f4-77b5-4c22-a3a7-2c56f7a657e1" \
  -d '{ "accountId": "66b2e19d8c3f5a7e9d0b1c2d", "message": "Yes, still available. Want me to hold it for you?" }'
```
</Tab>
</Tabs>

Response (`200`):

```json
{
  "success": true,
  "data": {
    "messageId": "aWdfZAG1faXRlbToxOklHTWVzc2FnZAUlEOjE3ODQx",
    "conversationId": "66c3d2ae7b4f6c8d0e1f2a3b"
  }
}
```

The `200` means accepted. Delivery status arrives through the same webhook stream that writes your inbox:

<Mermaid
  chart={`sequenceDiagram
  participant UI as Customer UI
  participant BE as Your backend
  participant Z as Zernio
  UI->>BE: reply
  BE->>Z: POST /v1/inbox/conversations/{id}/messages
  Z-->>BE: 200, accepted, not yet delivered
  alt delivery succeeds
    Z-->>BE: webhook message.sent
    Z-->>BE: webhook message.delivered / message.read
    BE-->>UI: show delivered / read
  else delivery fails
    Z-->>BE: webhook message.failed (error details)
    BE-->>UI: show the error inline and offer a retry
  end`}
/>

Run a customer's burst of sends (a "reply to all" feature, an automation) through a queue per customer. The rate limit applies to your key as a whole.

On a `429`, wait for the `Retry-After` header before retrying, as the [analytics worker](/multi-tenant/analytics#step-2-run-a-sync-worker) does.

## Step 3: Backfill with the list endpoint

When a customer's accounts connect, call `GET /v1/inbox/conversations` with `profileId` and page with `cursor`. Then fetch [messages](/messages/get-inbox-conversation-messages) per conversation.

Run the same sweep on a schedule to catch anything a missed webhook left behind.

With [zero content retention](/security/zero-content-retention) on a customer's profile, the sweep returns ids and metadata only, with message text `null`. It cannot recover the content of a missed webhook.

The endpoint aggregates DMs across the customer's messaging accounts (Facebook, Instagram, X, Bluesky, Reddit, Telegram, WhatsApp, SMS, Slack, LINE, WeChat).

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: conversations } = await zernio.messages.listInboxConversations({
  query: {
    profileId: '66a1f0c2a4b9d3e8f1a2b3c4',
    status: 'active',
    limit: 50,
  },
});

console.log(conversations.pagination.nextCursor);
```
</Tab>
<Tab value="Python">
```python
conversations = client.messages.list_inbox_conversations(
    profile_id="66a1f0c2a4b9d3e8f1a2b3c4",
    status="active",
    limit=50,
)

print(conversations["pagination"]["nextCursor"])
```
</Tab>
<Tab value="curl">
```bash
curl "https://zernio.com/api/v1/inbox/conversations?profileId=66a1f0c2a4b9d3e8f1a2b3c4&status=active&limit=50" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```
</Tab>
</Tabs>

Response (`200`):

```json
{
  "data": [
    {
      "id": "66c3d2ae7b4f6c8d0e1f2a3b",
      "platform": "instagram",
      "accountId": "66b2e19d8c3f5a7e9d0b1c2d",
      "participantName": "Jane",
      "lastMessage": "Hi, is this still available?",
      "updatedTime": "2027-01-04T14:00:03Z"
    }
  ],
  "pagination": { "hasMore": true, "nextCursor": "eyJ1cGRhdGVkVGltZSI6..." },
  "meta": { "accountsQueried": 3, "accountsFailed": 0, "failedAccounts": [] }
}
```

Check `meta.accountsFailed` on every sweep.

Accounts listed in `meta.failedAccounts` have token problems. That is your cue to run the [reconnect loop](/multi-tenant#step-5-monitor-account-health) for that customer.

<Callout type="warn">
Run the onboarding sweep twice for Instagram and Facebook. Re-run it an hour later, or let the scheduled sweep pick it up.
</Callout>

When one of these accounts connects, Zernio replays the DM history it already holds on Meta into the inbox, in the background. That replay can finish after your sweep has walked the list.

Replayed conversations keep their real `lastMessageAt`. So a 2-year-old conversation sorts 2 years back, on pages you already read, and the replay fires no webhooks.

To report inbox performance to a customer (volume, response time, heatmap, source breakdown), the [inbox analytics endpoints](/inbox-analytics/get-inbox-volume) take the same `profileId` filter.

## If it fails

A `400` from Step 2 with `code: "PLATFORM_LIMITATION"` means the platform does not offer what you sent, for example an attachment on a Bluesky or Reddit DM:

```json
{
  "error": "Attachments are not supported for bluesky conversations",
  "code": "PLATFORM_LIMITATION"
}
```

Send the message without the attachment.

A `500` means the platform rejected or failed the send. Zernio never retries a send internally.

It is ambiguous: the platform may already have accepted the message. The `500` also releases your `Idempotency-Key`, so a retry with the same key sends for real.

Reconcile before you retry. List the conversation's [messages](/messages/get-inbox-conversation-messages) first. Treat an empty result as inconclusive, not as proof nothing was sent.

The key covers the other case, where the send succeeded and the response never reached you. That retry replays the original `200` with `Idempotent-Replayed: true`.

## Related

- [Build a platform](/multi-tenant): the profile-per-customer model.
- [Analytics dashboards](/multi-tenant/analytics): the same architecture applied to metrics.
- [Inbox webhooks](/webhooks/inbox): full payload schemas for every message event.
- [WhatsApp inbox](/platforms/whatsapp/inbox): templates and the 24-hour window.