Verify Tawk.to webhooks

Every tawk.to webhook carries an X-Tawk-Signature header, the lowercase hex HMAC-SHA1 of the raw request body, keyed with that webhook's secret key. Recomputing it shows the request came from tawk.to and the body wasn't changed. No timestamp is signed, so it doesn't stop a replayed request. tawk.to's docs give samples in Node.js, PHP and Ruby.

The facts

Signature header
X-Tawk-Signature

Format: <lowercase hex>

Scheme
HMAC-SHA1
Signed material
{raw body}

The request body exactly as sent, with no timestamp or event ID.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Tawk.to webhook secret

Each webhook has its own secret key, which tawk.to uses to sign every request to that webhook. Keep it in an environment variable, not in source code.

  • Webhooks are managed per property under Administration > Settings > Webhooks.
  • tawk.to's docs don't say where the dashboard shows the key, what format it has or how to rotate it.

Source: Tawk.to docs ↗

Code

express/src/index.js
javascript
// Generated with: tawk-to-webhooks skill
// https://github.com/hookdeck/webhook-skills

require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify a tawk.to webhook: lowercase hex HMAC-SHA1 of the raw body,
 * keyed with the webhook secret, sent in X-Tawk-Signature.
 */
function verifyTawkSignature(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) return false;
  const expected = crypto.createHmac('sha1', secret).update(rawBody).digest('hex');
  const a = Buffer.from(signatureHeader, 'utf8');
  const b = Buffer.from(expected, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// '*/*' reads the raw body whatever the Content-Type, so verification never depends on it
app.post('/webhooks/tawk-to', express.raw({ type: '*/*' }), (req, res) => {
  const signature = req.headers['x-tawk-signature'];

  if (!signature) {
    return res.status(400).send('Missing X-Tawk-Signature header');
  }
  if (!Buffer.isBuffer(req.body) || !verifyTawkSignature(req.body, signature, process.env.TAWK_WEBHOOK_SECRET)) {
    console.error('tawk.to signature verification failed');
    return res.status(400).send('Invalid signature');
  }

  let payload;
  try {
    payload = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.status(400).send('Invalid JSON');
  }

  // X-Hook-Event-Id is stable across retries: use it for idempotency
  const eventId = req.headers['x-hook-event-id'];
  console.log(`Received ${payload.event} (event id: ${eventId})`);

  switch (payload.event) {
    case 'chat:start':
      console.log('Chat started:', payload.chatId, 'visitor:', payload.visitor?.name);
      break;
    case 'chat:end':
      console.log('Chat ended:', payload.chatId);
      break;
    case 'chat:transcript_created':
      console.log('Transcript created:', payload.chat?.id, 'messages:', payload.chat?.messages?.length);
      break;
    case 'ticket:create':
      console.log('Ticket created:', payload.ticket?.id, payload.ticket?.subject);
      break;
    default:
      console.log('Unhandled event:', payload.event);
  }

  res.status(200).json({ received: true });
});

const PORT = process.env.PORT || 3000;
if (require.main === module) {
  app.listen(PORT, () => console.log(`tawk.to webhook server listening on port ${PORT}`));
}

module.exports = { app, verifyTawkSignature };
nextjs/app/webhooks/tawk-to/route.ts
typescript
// Generated with: tawk-to-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

// tawk.to: lowercase hex HMAC-SHA1 of the raw body, keyed with the webhook secret
function verifyTawkSignature(
  rawBody: string,
  signatureHeader: string | null,
  secret: string | undefined
): boolean {
  if (!signatureHeader || !secret) return false;
  const expected = crypto.createHmac('sha1', secret).update(rawBody).digest('hex');
  const a = Buffer.from(signatureHeader, 'utf8');
  const b = Buffer.from(expected, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

export async function POST(request: NextRequest) {
  // Raw body: do not use request.json() before verifying
  const body = await request.text();
  const signature = request.headers.get('x-tawk-signature');

  if (!signature) {
    return NextResponse.json({ error: 'Missing X-Tawk-Signature header' }, { status: 400 });
  }
  if (!verifyTawkSignature(body, signature, process.env.TAWK_WEBHOOK_SECRET)) {
    console.error('tawk.to signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let payload: any;
  try {
    payload = JSON.parse(body);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  // X-Hook-Event-Id is stable across retries: use it for idempotency
  const eventId = request.headers.get('x-hook-event-id');
  console.log(`Received ${payload.event} (event id: ${eventId})`);

  switch (payload.event) {
    case 'chat:start':
      console.log('Chat started:', payload.chatId, 'visitor:', payload.visitor?.name);
      break;
    case 'chat:end':
      console.log('Chat ended:', payload.chatId);
      break;
    case 'chat:transcript_created':
      console.log('Transcript created:', payload.chat?.id, 'messages:', payload.chat?.messages?.length);
      break;
    case 'ticket:create':
      console.log('Ticket created:', payload.ticket?.id, payload.ticket?.subject);
      break;
    default:
      console.log('Unhandled event:', payload.event);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: tawk-to-webhooks skill
# https://github.com/hookdeck/webhook-skills

import hashlib
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()


def verify_tawk_signature(raw_body: bytes, signature: str | None, secret: str | None) -> bool:
    """tawk.to: lowercase hex HMAC-SHA1 of the raw body, keyed with the webhook secret."""
    if not signature or not secret:
        return False
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha1).hexdigest()
    return hmac.compare_digest(signature.encode(), expected.encode())


@app.post("/webhooks/tawk-to")
async def tawk_webhook(request: Request):
    # Raw bytes: do not parse JSON before verifying
    raw_body = await request.body()
    signature = request.headers.get("x-tawk-signature")

    if not signature:
        raise HTTPException(status_code=400, detail="Missing X-Tawk-Signature header")
    if not verify_tawk_signature(raw_body, signature, os.getenv("TAWK_WEBHOOK_SECRET")):
        raise HTTPException(status_code=400, detail="Invalid signature")

    try:
        payload = json.loads(raw_body)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    # X-Hook-Event-Id is stable across retries: use it for idempotency
    event_id = request.headers.get("x-hook-event-id")
    event = payload.get("event")
    print(f"Received {event} (event id: {event_id})")

    if event == "chat:start":
        print("Chat started:", payload.get("chatId"))
    elif event == "chat:end":
        print("Chat ended:", payload.get("chatId"))
    elif event == "chat:transcript_created":
        print("Transcript created:", (payload.get("chat") or {}).get("id"))
    elif event == "ticket:create":
        print("Ticket created:", (payload.get("ticket") or {}).get("id"))
    else:
        print("Unhandled event:", event)

    return {"received": True}

From hookdeck/webhook-skills ↗

Or install the Tawk.to webhooks skill:

npx skills add hookdeck/webhook-skills --skill tawk-to-webhooks

Common failures

Body parsed before verification

The signature covers the exact bytes tawk.to sent, and re-serialising parsed JSON can change them. Verify the raw body, then parse it.

Raw body captured only for JSON requests

tawk.to's Node.js sample keeps the raw body only for application/json, and its docs don't state the Content-Type it sends. Capture the raw body whatever the content type.

Wrong webhook's secret

Each webhook has its own secret key. If several webhooks share a receiver, give each its own path so you can pick the right key.

Wrong algorithm or encoding

The docs list only HMAC-SHA1, encoded as hex with no prefix. Code copied from a vendor that uses SHA-256 or base64 won't match.

From Hookdeck's Tawk.to guide

Let Event Gateway verify Tawk.to signatures.

Event Gateway verifies the signature on each Tawk.to delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Tawk.to. Facts are compiled from public sources and linked inline.