# Z-API Omni quickstart in Node.js: send and receive with Express

> Send a WhatsApp text through the Z-API Omni API and receive signed webhooks in Express: Bearer auth, HMAC over five fields, gzip, replay and dedupe.

Published 2026-11-05. Z-API Omni team.

To send and receive messages with Z-API Omni in Node.js, you need one file and three values: a Secret Key, a channel ID and a webhook secret. The Express file below sends a TEXT message with `POST /v1/channels/{channelId}/messages` and receives signed webhooks on one route. It needs Node.js 24 or later and Express 5, nothing else.

## Set up the workspace

Node.js 24 and 26 are both LTS lines, and 26 is the newest ([Node.js releases](https://nodejs.org/en/about/previous-releases), accessed 2026-11-05).

```bash
npm install express@5
```

### Generate the Secret Key

In the dashboard at app.omni.z-api.io, open the Security menu and generate a Secret Key. It goes in the `Authorization: Bearer` header of every API call and must stay on your backend ([Omni authentication](https://developer.omni.z-api.io/en/authentication), accessed 2026-11-05). Don't confuse it with the Public Key, which is for the channel-connection SDK.

### Create and connect a channel

Create the channel by API so you get its ID back. The body uses the example values from the create-channel page.

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
curl -s -X POST https://api.omni.z-api.io/v1/channels \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "My WhatsApp channel", "type": "META_WHATSAPP"}'
```
<!-- TODO:test Omni: POST /v1/channels returns 201 with id and token; a repeated name returns 409 channel_name_in_use -->

A 201 returns `id`, the channelId every later call uses, and a `token`. A 409 with `"error": "channel_name_in_use"` means the name is taken ([Omni create channel](https://developer.omni.z-api.io/en/channels/create-channel), accessed 2026-11-05). Keep the `id`, because listing or reading channels requires the ENTERPRISE role. Then connect it to your number in the dashboard ("via dashboard or SDK", per the page).

### Register a signed webhook

The body below is the "With HMAC signature" example from the create-webhook page, with the URL replaced by a placeholder.

```bash
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
curl -s -X POST "https://api.omni.z-api.io/v1/channels/$OMNI_CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://YOUR_DOMAIN/webhooks/omni", "events": ["MESSAGE_RECEIVED", "MESSAGE_STATUS"], "signing": true}'
```
<!-- TODO:test Omni: POST /v1/channels/{channelId}/webhooks with signing true returns 201 with a 64-character hex secret -->

The 201 carries a `secret` of 64 hex characters. Store it as `OMNI_WEBHOOK_SECRET` now, because "it will not be shown again in any other call" ([Omni create webhook](https://developer.omni.z-api.io/en/webhooks/create-webhook), accessed 2026-11-05). Every later `PATCH` with `signing: true` generates a new secret and invalidates the old one ([Omni HMAC signing](https://developer.omni.z-api.io/en/webhooks/signature)). Leave `signing` out of a PATCH unless you mean to rotate.

### Give the webhook a public URL

Omni refuses `localhost`, `.localhost`, `.internal`, dotless names, non-public IPs and hosts missing from DNS, with a 400 ([Omni webhooks introduction](https://developer.omni.z-api.io/en/webhooks/introduction), accessed 2026-11-05). Deploy the file to a public host, or put a tunnel in front of port 3000 as in [the local webhook testing guide](/academy/articles/whatsapp-webhook-local-testing-ngrok/).

## The full file

```javascript
// omni-quickstart.js
// node omni-quickstart.js selftest
// node omni-quickstart.js send 5511999999999 "Hello!"
// node omni-quickstart.js serve
const express = require('express');
const crypto = require('node:crypto');

const API_BASE = process.env.OMNI_API_BASE || 'https://api.omni.z-api.io';
const PORT = Number(process.env.PORT || 3000);
const TOLERANCE_SECONDS = 300;
const KEEP_MS = 24 * 60 * 60 * 1000;

async function sendText(phone, text) {
  const { OMNI_SECRET_KEY, OMNI_CHANNEL_ID } = process.env;
  if (!OMNI_SECRET_KEY || !OMNI_CHANNEL_ID) throw new Error('Set OMNI_SECRET_KEY and OMNI_CHANNEL_ID');
  const res = await fetch(`${API_BASE}/v1/channels/${encodeURIComponent(OMNI_CHANNEL_ID)}/messages`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${OMNI_SECRET_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      recipient: { identifier: phone },
      content: { type: 'TEXT', body: { message: text } },
    }),
  });
  const raw = await res.text();
  let data = {};
  try {
    data = JSON.parse(raw) ?? {};
  } catch {}
  if (res.ok && data.messageId) return data.messageId;
  if (res.status === 422 && data.subCode === 'CHANNEL_DISCONNECTED') {
    throw new Error('Channel disconnected: reconnect it in the dashboard, then send again');
  }
  throw new Error(`Send refused: HTTP ${res.status} ${raw}`);
}

// Returns null when the request is valid, or the reason it is not.
function verifySignature(secret, body, signatureHeader, idempotencyKey, now = Math.floor(Date.now() / 1000)) {
  if (typeof signatureHeader !== 'string' || typeof idempotencyKey !== 'string') return 'missing headers';
  const parts = {};
  for (const pair of signatureHeader.split(',')) {
    const i = pair.indexOf('=');
    if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
  }
  const { t, v1 } = parts;
  if (!/^[0-9]{1,12}$/.test(t ?? '') || !/^[0-9a-f]{64}$/.test(v1 ?? '')) return 'malformed signature header';

  const last = idempotencyKey.lastIndexOf(':');
  const prev = last > 0 ? idempotencyKey.lastIndexOf(':', last - 1) : -1;
  if (prev < 0) return 'malformed idempotency key';
  const topic = idempotencyKey.slice(0, prev);
  const partition = idempotencyKey.slice(prev + 1, last);
  const offset = idempotencyKey.slice(last + 1);

  const canonical = Buffer.concat([Buffer.from(`${t}\n${topic}\n${partition}\n${offset}\n`, 'utf8'), body]);
  const expected = crypto.createHmac('sha256', secret).update(canonical).digest();
  if (!crypto.timingSafeEqual(expected, Buffer.from(v1, 'hex'))) return 'bad signature';
  if (Math.abs(now - Number(t)) > TOLERANCE_SECONDS) return 'stale timestamp';
  return null;
}

const seen = new Map(); // delivery id -> first seen (ms). Demo only: use a table with a unique key in production.

function firstDelivery(deliveryId) {
  const now = Date.now();
  for (const [id, at] of seen) {
    if (now - at <= KEEP_MS) break; // Map keeps insertion order, so the oldest entries come first
    seen.delete(id);
  }
  if (seen.has(deliveryId)) return false;
  seen.set(deliveryId, now);
  return true;
}

function handleEvent(payload) {
  const msg = payload?.message;
  if (!msg || typeof msg !== 'object') {
    console.log('event without a message object');
    return;
  }
  if (msg.metadata?.from_me !== false) {
    console.log(`skip ${msg._id}: from_me is ${msg.metadata?.from_me}`);
    return;
  }
  const first = msg.contents?.[0];
  if (first?.type === 'TEXT') {
    console.log(`text from ${msg.sender?.identifier} on channel ${msg.channel_id}: ${first.message}`);
  } else {
    console.log(`non-text message ${msg._id}`);
  }
}

function serve() {
  const secret = process.env.OMNI_WEBHOOK_SECRET;
  if (!secret) {
    console.error('Set OMNI_WEBHOOK_SECRET');
    process.exit(1);
  }
  const app = express();
  // inflate: true (the default) hands us the gzip body already decompressed.
  const rawJson = express.raw({ type: 'application/json', inflate: true, limit: '1mb' });

  app.post('/webhooks/omni', rawJson, (req, res) => {
    if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
    const deliveryId = req.get('x-webhook-delivery-id');
    const problem = verifySignature(secret, req.body, req.get('x-webhook-signature'), req.get('x-idempotency-key'));
    if (problem) {
      console.warn(`rejected delivery ${deliveryId ?? '-'}: ${problem}`);
      return res.sendStatus(401);
    }
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch {
      return res.sendStatus(400);
    }
    if (deliveryId && !firstDelivery(deliveryId)) return res.sendStatus(200);
    res.sendStatus(200);
    setImmediate(() => {
      try {
        handleEvent(payload);
      } catch (err) {
        console.error('handler failed', err);
      }
    });
  });

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

function selfTest() {
  // Test vector from the HMAC signing page of the Omni docs.
  const secret = 'a7f3c81e9d2b4605f1a8c3e7b9d40f6218273645a8b9c0d1e2f3041526374859';
  const body = Buffer.from('[{"field":"message_template_status_update","identifier":"01A0A4FBC8CD7DCBBBFAA8382F5514A5","type":"TEMPLATE_STATUS","value":{"event":"APPROVED","message_template_category":"UTILITY","message_template_id":"1587155656151346","message_template_language":"pt_BR","message_template_name":"exemplo_teste_assinatura_webhook","reason":"NONE"},"waba_id":"845974408299669"}]', 'utf8');
  const signature = 't=1789474359,v1=c9a6812419c87dc26841fd802f1b4704f7dfe868b178ba55f9c432642be67230';
  const key = 'webhook.delivery.event:0:539402';
  const t = 1789474359;
  const checks = [
    ['doc vector', verifySignature(secret, body, signature, key, t), null],
    ['tampered body', verifySignature(secret, Buffer.concat([body, Buffer.from(' ')]), signature, key, t), 'bad signature'],
    ['stale t', verifySignature(secret, body, signature, key, t + TOLERANCE_SECONDS + 1), 'stale timestamp'],
  ];
  let ok = body.length === 364;
  console.log(`body length ${body.length} bytes (content-length in the doc: 364)`);
  for (const [name, got, want] of checks) {
    const pass = got === want;
    ok = ok && pass;
    console.log(`${pass ? 'PASS' : 'FAIL'} ${name}: ${got ?? 'valid'}`);
  }
  return ok;
}

const [command, ...args] = process.argv.slice(2);
if (command === 'selftest') {
  process.exitCode = selfTest() ? 0 : 1;
} else if (command === 'send' && args[0]) {
  sendText(args[0], args.slice(1).join(' ') || 'Hello!')
    .then((id) => console.log(`accepted, messageId ${id}`))
    .catch((err) => {
      console.error(err.message);
      process.exitCode = 1;
    });
} else if (command === 'serve') {
  serve();
} else {
  console.error('usage: node omni-quickstart.js selftest | send PHONE [TEXT] | serve');
  process.exitCode = 2;
}
```
<!-- TODO:test Omni: sendText against a live channel, and a real signed delivery (plain and gzip) accepted by the serve route -->

Set `OMNI_API_BASE` only to point the send at a mock. Run `node omni-quickstart.js selftest` first. It checks the verifier against Omni's signing-page example and prints three PASS lines.

## Verify the signature over five fields

Omni's HMAC covers five fields joined by a bare `\n`: `t`, `topic`, `partition`, `offset` and the raw body ([Omni HMAC signing](https://developer.omni.z-api.io/en/webhooks/signature), accessed 2026-11-05). There is no `\r` and no trailing newline. `t` and `v1` come from `x-webhook-signature: t=...,v1=...`. The other three come from `x-idempotency-key`, formatted `{topic}:{partition}:{offset}`. The topic can contain dots, so the code splits that header on its last two colons.

The verifier follows Omni's Node sample, with a `now` argument for testing. It returns a reason string for your log. It rejects a `v1` that isn't 64 lowercase hex characters, so `timingSafeEqual` never throws on unequal lengths.

### Gzip and express.raw

"Requests of 1024 bytes or more are sent with `content-encoding: gzip`", and the HMAC covers the uncompressed bytes. `express.raw()` "supports automatic inflation of `gzip` and `deflate` encodings", with `inflate` on by default ([Express 5 API](https://expressjs.com/en/5x/api/express/)). That means `req.body` already holds the decompressed bytes. So pass no encoding to the verifier, as Omni's page says: "If your HTTP framework decompresses the body for you, use the body it hands you."

`type` defaults to `application/octet-stream`, so without `type: 'application/json'` the body is `undefined`. Omni publishes no maximum payload size, so the `1mb` limit (default `100kb`) is this guide's choice. Mount the parser on this route only, because a global `express.json()` registered first would consume the stream.

### Reject stale timestamps

The signing page calls 5 minutes "a reasonable value", and its samples use `toleranceSeconds = 300`. Keep the server clock synced. The docs don't say whether a retry hours later carries a new `t`. If retries show up in your log as stale, check this first.
<!-- TODO:test Omni: confirm a retried delivery (x-webhook-attempt > 1) carries a fresh t in x-webhook-signature -->

## Answer 200 within 5 seconds, then deduplicate

A delivery succeeds only on a 2xx "within 5 seconds" ([Omni delivery and retries](https://developer.omni.z-api.io/en/webhooks/delivery), accessed 2026-11-05). The route answers 200 and hands the payload to `setImmediate`.

| Your response | What Omni does |
|---|---|
| 2xx within 5 s | Delivered, no retry |
| No response in 5 s, connection error, 408, 429 or 5xx | Sends again after 1 min, 5 min, 30 min, 2 h, 6 h and 12 h |
| Any other 4xx, or 3xx | No retry |

That is up to 7 attempts within 23 hours. Meta's equivalent is in [webhook retries when the endpoint is down](/academy/articles/whatsapp-webhook-retries-endpoint-down/). A failed signature check returns 401, which is never retried. That suits forged requests, but a bug in your verifier drops real events for good. Watch the `rejected delivery` log lines after you go live.

The delivery page says to deduplicate on `x-webhook-delivery-id` and keep processed IDs "for at least 24 hours". The `Map` loses everything on restart, so use a unique key in your database ([duplicate webhooks and idempotency](/academy/articles/n8n-duplicate-webhooks-idempotency/)). The check runs after verification, so a forged request can't add an ID.

If the process dies after the 200, the event is gone. For anything you can't lose, write the raw body to a queue or table first ([webhook queue architecture](/academy/articles/whatsapp-webhook-queue-architecture-workers/)). Order isn't guaranteed either: sort by `moment` in the body and never move a status backward ([out-of-order webhooks](/academy/articles/whatsapp-webhooks-out-of-order-message-sequencing/)).

## Read the message text

In the default format, every event has a top-level `message` object and a `messageEventType`. That field is "currently `NEW_MESSAGE` for all message events" ([Omni payload structure](https://developer.omni.z-api.io/en/webhooks/payloads), accessed 2026-11-05). Text sits in `message.contents[0].message` when `contents[0].type` is `TEXT`. `metadata.from_me` is "`true` when sent by the business; `false` when received from the contact".

The page's only TEXT sample is an API send with `from_me: true`, and the payloads page shows no inbound or status sample. So `handleEvent` prints text only when `from_me` is `false` and logs the rest without guessing at fields.

## Send a message and read the errors

This is the request body from Omni's send-text page, with the message string changed to `Hello!`.

```json
{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "TEXT",
    "body": { "message": "Hello!" }
  }
}
```

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
node omni-quickstart.js send 5511999999999 "Hello!"
```
<!-- TODO:test Omni: send TEXT returns 200 with messageId; a disconnected channel returns 422 BUSINESS_RULE_VIOLATION / CHANNEL_DISCONNECTED -->

A 200 returns `messageId`, a 32-character uppercase hex string ([Omni send text](https://developer.omni.z-api.io/en/messages/send-text), accessed 2026-11-05). It means the API accepted the message. Status updates arrive later as `MESSAGE_STATUS` events; add `MESSAGE_DELIVERY` to `events` for delivery confirmations. Handle refusals by `code` and `subCode`, because the message text "may change".

| Status | `code` / `subCode` | Meaning |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The body does not fit the content type |
| 401 | `"error": 401` | Invalid or missing Secret Key |
| 422 | `BUSINESS_RULE_VIOLATION` / `CHANNEL_DISCONNECTED` | Not sent and not kept: reconnect, then send again |
| 422 | `BUSINESS_RULE_VIOLATION`, no `subCode` | Another send rule refused it; the reason is in `message` |
| 502 | varies | A failure on Omni's side |

The rows come from Omni's [send errors table](https://developer.omni.z-api.io/en/messages/introduction) (accessed 2026-11-05). On WhatsApp, a free-form TEXT needs an open 24-hour window; outside it you send a `TEMPLATE`. If the workspace has IP restriction on, a call from an unlisted IP gets a 400 ([Omni IP restriction](https://developer.omni.z-api.io/en/security/ip-restriction), accessed 2026-11-05).

## Test the receiver locally

Sign a request yourself and post it to `localhost`. Start the server with the webhook secret, and export the same value in the terminal you test from.

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
node omni-quickstart.js serve
```

The sample is the TEXT payload from Omni's payloads page, compacted to one line. The `sed` copy flips `from_me` to `false` so the inbound branch runs. Each request is gzipped, so the inflate path runs too.

```bash
cat > sample.json <<'EOF'
{"message":{"_id":"019E6F1A93FE78DCB54332F9FF0CCAE7","tenant":"019DCEB3E93B7077B2447616B6DC8B91","tenant_owner":"email@z-api.io","channel_id":"019E4C54B1B375A28970B605CA9B03C3","created_by":"BARLING","created":1779980473342,"metadata":{"@class":".Metadata","forwarded":false,"from_api":true,"from_me":true,"middleware":"META_WHATSAPP","moment":1779980473342},"sender":{"@class":".Sender","identifier":"BARLING_SYSTEM","name":"Barling System"},"recipient":{"@class":".Recipient","identifier":"5544936181064","name":"5544936181064"},"contents":[{"@class":".TextContent","identifier":"019E6F1A93FE78DCB542303FF18D389A","internal_information":{},"message":"Hello! We have incredible news waiting for you.","state_items":[{"@class":".StateItem","identifier":"019E6F1A93FE78DCB5418E8D9D007FFB","integration_message_ids":[],"moment":1779980473342,"state":{"@class":".Pending","name":"PENDING"}}],"type":"TEXT"}],"attachments":[],"actions":[],"webhook_processed":false},"messageEventType":"NEW_MESSAGE"}
EOF
sed 's/"from_me":true/"from_me":false/' sample.json > inbound.json

post_signed() { # FILE OFFSET URL
  T=$(date +%s)
  SIG=$( { printf '%s\nwebhook.delivery.event\n0\n%s\n' "$T" "$2"; cat "$1"; } \
    | openssl dgst -sha256 -hmac "$OMNI_WEBHOOK_SECRET" | awk '{print $NF}')
  gzip -c "$1" | curl -s -o /dev/null -w '%{http_code}\n' -X POST "$3" \
    -H 'content-type: application/json' -H 'content-encoding: gzip' \
    -H "x-idempotency-key: webhook.delivery.event:0:$2" \
    -H "x-webhook-signature: t=$T,v1=$SIG" \
    -H "x-webhook-delivery-id: test-$2" -H 'x-webhook-attempt: 1' \
    --data-binary @-
}

post_signed sample.json 1 http://localhost:3000/webhooks/omni
post_signed inbound.json 2 http://localhost:3000/webhooks/omni
post_signed inbound.json 2 http://localhost:3000/webhooks/omni
```

All three print `200`. The server logs `skip ... from_me is true` for the first and the text line for the second. The third reuses delivery ID `test-2`, so it logs nothing. Export a different `OMNI_WEBHOOK_SECRET` in the test terminal only and the server answers 401 with `bad signature`.

## How this differs from Meta's raw webhook

Meta signs the body alone with your app secret in `X-Hub-Signature-256`. Its envelope is `entry[].changes[].value`, as [the Express Cloud API webhook guide](/academy/articles/whatsapp-webhook-nodejs-express-receive-messages/) shows. Omni signs five fields with a secret per webhook, adds a timestamp and sends a delivery ID for dedupe. Its body is Omni's own `message` envelope, or the `Z_API` or `CHATWOOT` format if you set `payloadFormat`. The webhook pages describe no GET challenge step; you register the URL with an API call.

The same receiver is in [the FastAPI quickstart](/academy/articles/z-api-omni-quickstart-python-fastapi/) and [the PHP quickstart](/academy/articles/z-api-omni-quickstart-php/). One Omni subscription covers WhatsApp, Messenger, Instagram and Telegram, with webhooks included without limit. [View documentation](https://developer.omni.z-api.io/en)

*Z-API Omni team*
