Webhook server

Receive webhooks in a Node.js server without a framework. Verify the signature before processing each event. The server calls no API and needs no API key.

Before you start

  • PLATIC_WEBHOOK_SECRET: the signing secret you gave the webhook (webhooks.create({ secret })).
  • A public HTTPS URL that reaches the server: a reverse proxy or a tunnel.
  • Node.js 20.3 or newer and npm install platic-sdk.

Signatures, responses and repeated events

  • Reads the request body as raw bytes, up to 1 MiB, and answers 413 beyond that.
  • Verifies the signature with parseWebhookEvent. A failed delivery gets 401 and is not acted on.
  • Answers 200 first, then does the work, so Platica is not kept waiting.
  • Skips repeated events using an in-memory list of the last 10,000 ids. Restarting the process clears the list.
  • Handles three events and logs any other.

The code

import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import { parseWebhookEvent, WEBHOOK_SIGNATURE_HEADER, WebhookVerificationError } from "platic-sdk";

const secret = process.env.PLATIC_WEBHOOK_SECRET ?? "";
if (!secret) {
  console.error("Set PLATIC_WEBHOOK_SECRET to the webhook's signing secret.");
  process.exit(1);
}
const PATH = "/webhooks/platica";
const MAX_BODY_BYTES = 1024 * 1024;
const HOST = process.env.HOST ?? "127.0.0.1";

// The same event can arrive more than once, and the signature does not stop someone who captured a delivery from
// sending it again: remember the ids you handled. This is one process's memory; with several, keep them in a database.
const seen = new Set<string>();
function firstTime(id: string): boolean {
  if (seen.has(id)) return false;
  seen.add(id);
  const oldest = seen.values().next().value;
  if (seen.size > 10_000 && oldest !== undefined) seen.delete(oldest);
  return true;
}

async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
  if (req.method !== "POST" || req.url !== PATH) return void res.writeHead(404).end();

  // The signature covers the exact bytes Platica sent: read them as they are, never a parsed and re-serialized body.
  const chunks: Buffer[] = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > MAX_BODY_BYTES) return void res.writeHead(413).end();
    chunks.push(chunk);
  }

  let event;
  try {
    event = await parseWebhookEvent({ payload: Buffer.concat(chunks), signature: req.headers[WEBHOOK_SIGNATURE_HEADER], secret });
  } catch (error) {
    if (!(error instanceof WebhookVerificationError)) throw error;
    console.warn(`rejected a delivery: ${error.reason}`);
    return void res.writeHead(401).end();
  }

  // Answer first; do the slow work after (or hand it to a queue).
  res.writeHead(200, { "content-type": "application/json" }).end("{}");
  if (!firstTime(event.id)) return;

  switch (event.event) {
    case "message.created":
      console.log(`${event.id} message.created: ${event.data.message.direction} message in conversation ${event.data.conversation.id}`);
      break;
    case "conversation.status.updated":
      console.log(`${event.id} conversation ${event.data.conversation.id} is now ${event.data.conversation.status}`);
      break;
    case "client.created":
      console.log(`${event.id} new contact ${event.data.id}`);
      break;
    default:
      // Platica may add events: accept them, and read what every event carries.
      console.log(`${event.id} ${event.event} on ${event.resourceType ?? "?"} ${event.resourceId ?? ""}`);
  }
}

const server = createServer((req, res) => {
  handle(req, res).catch((error) => {
    console.error(error);
    if (!res.headersSent) res.writeHead(500).end();
  });
});

server.listen(Number(process.env.PORT ?? 3000), HOST, () => {
  const address = server.address();
  const port = typeof address === "object" && address !== null ? address.port : process.env.PORT;
  console.log(`listening on http://${HOST}:${port}${PATH}`);
});

Run it

Save the code in webhook-server.ts and run it with tsx.

PLATIC_WEBHOOK_SECRET=... PORT=3000 npx tsx webhook-server.ts

PORT defaults to 3000 and HOST to 127.0.0.1. Use an HTTPS proxy or tunnel to make the server URL public. Register it with the same signing secret:

await platic.webhooks.create({
  name: "My app",
  url: "https://example.com/webhooks/platica",
  events: ["message.created"],
  secret: process.env.PLATIC_WEBHOOK_SECRET,
});

What to expect

listening on http://127.0.0.1:3000/webhooks/platica
<event id> message.created: inbound message in conversation …

Platica checks the URL with a HEAD request before activating the webhook. It accepts any status below 500, including this server's 404. If a delivery has a missing or incorrect signature, the server logs rejected a delivery: <reason> and responds with 401.

API reference used

Receive messages and cases

Verify the signature and process the event

Implement this endpoint on your server. Verify the signature over the raw body, respond with 2xx promptly and skip events already processed. The X-Webhook-Signature header contains sha256=<hmac_sha256(secret, rawBody)>. (Delivery and signatures)

import { createServer } from "node:http";
import { parseWebhookEvent, WEBHOOK_SIGNATURE_HEADER, WebhookVerificationError } from "platic-sdk";

const secret = process.env.PLATIC_WEBHOOK_SECRET!;
const seen = new Set<string>(); // with several processes, keep the ids in a database

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/webhooks/platica") return void res.writeHead(404).end();

  // The signature covers the exact bytes Platica sent: read them as they are.
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(chunk);

  let event;
  try {
    event = await parseWebhookEvent({
      payload: Buffer.concat(chunks),
      signature: req.headers[WEBHOOK_SIGNATURE_HEADER],
      secret,
    });
  } catch (error) {
    if (error instanceof WebhookVerificationError) return void res.writeHead(401).end();
    throw error;
  }

  // Answer first; do the slow work after, or hand it to a queue.
  res.writeHead(200).end("{}");
  if (seen.has(event.id)) return;
  seen.add(event.id);

  switch (event.event) {
    case "message.created":
      console.log("message in conversation", event.data.conversation.id);
      break;
    case "case.created":
      console.log("new case", event.resourceId);
      break;
    default:
      console.log(event.event, event.resourceType, event.resourceId);
  }
}).listen(3000);

Without the SDK, compute the same HMAC yourself over the raw body and compare it with crypto.timingSafeEqual; the full example is in Delivery and signatures.

Store each event's id and skip repeats. An event can arrive more than once, and the signature has no date to prevent replaying a captured delivery.

Next steps