Verify HubSpot webhooks

HubSpot signs each request so you can confirm it came from HubSpot and wasn't changed. X-HubSpot-Signature-v3 holds a base64 HMAC-SHA256, keyed with your app's client secret, over the method, URI, body and X-HubSpot-Request-Timestamp, and you reject anything older than 5 minutes. Requests can also carry the older X-HubSpot-Signature, which signs no timestamp. HubSpot's Node, Python, PHP and Ruby clients include a signature helper.

These pages cover the events a HubSpot app subscribes to. Workflows are a separate feature: a workflow's Send a webhook action sends one record's data to a URL, with its own body and retry rules, and a webhook from another app can also trigger a workflow.

The facts

Signature header
X-HubSpot-Signature-v3

Format: <base64>

Scheme
HMAC-SHA256, base64
Signed material
{method}{uri}{body}{timestamp}

The HTTP method, the full URI HubSpot called with the listed percent-encoded characters decoded, the body as sent, then the X-HubSpot-Request-Timestamp header, with no separators.

Send timestamp
X-HubSpot-Request-Timestamp

Reject deliveries older than 5 minutes.

Legacy signature
X-HubSpot-Signature, X-HubSpot-Signature-Version

A plain SHA-256 hex digest, not an HMAC: secret + body for v1, secret + method + URI + body for v2, as named by X-HubSpot-Signature-Version.

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

HubSpot webhook secret

The key is your app's client secret. There's no separate webhook secret, and the same value also manages OAuth tokens. Keep it in an environment variable, not in source code.

  • Project-based app: on the project's Overview tab, click the app name, open the Auth tab and find Client secret under Client credentials.
  • Legacy public app: open the app and click the Auth tab.
  • Legacy private app: on the Auth tab of the app's settings, click Show secret.
  • One per app, so every account that installs the app gets requests signed with the same secret.
  • It isn't an access token or a developer API key.
  • Rotate it from the Auth tab with Rotate. HubSpot says the old secret is invalidated and describes no overlap, so plan for a cutover.
  • HubSpot's docs describe no test and live split.

Source: HubSpot docs ↗

Code

express/src/index.js
javascript
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();

// Behind a proxy/tunnel (Hookdeck, ngrok, etc.), trust X-Forwarded-* headers so
// req.protocol and req.get('host') match the public URL HubSpot called.
app.set('trust proxy', true);

const MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes

/**
 * Verify HubSpot v3 webhook signature.
 *
 * Signed content = method + URI + raw body + X-HubSpot-Request-Timestamp
 * Signature = base64(HMAC-SHA256(signed_content, app_client_secret))
 *
 * @param {object} args
 * @param {string} args.method - HTTP method, e.g. "POST"
 * @param {string} args.uri - Full request URI HubSpot called
 * @param {Buffer|string} args.rawBody - Raw request body
 * @param {string} args.timestamp - X-HubSpot-Request-Timestamp header value (ms)
 * @param {string} args.signature - X-HubSpot-Signature-v3 header value
 * @param {string} args.secret - HubSpot app Client Secret
 * @returns {boolean}
 */
function verifyHubSpotWebhook({ method, uri, rawBody, timestamp, signature, secret }) {
  if (!signature || !timestamp || !secret) return false;

  const ts = Number(timestamp);
  if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > MAX_AGE_MS) return false;

  const body = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : (rawBody || '');
  const signedContent = `${method}${uri}${body}${timestamp}`;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedContent, 'utf8')
    .digest('base64');

  try {
    return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  } catch {
    return false;
  }
}

// HubSpot webhook endpoint - must use raw body for HMAC verification
app.post('/webhooks/hubspot',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['x-hubspot-signature-v3'];
    const timestamp = req.headers['x-hubspot-request-timestamp'];

    // Reconstruct the URI HubSpot signed
    const uri = `${req.protocol}://${req.get('host')}${req.originalUrl}`;

    const valid = verifyHubSpotWebhook({
      method: req.method,
      uri,
      rawBody: req.body,
      timestamp,
      signature,
      secret: process.env.HUBSPOT_CLIENT_SECRET,
    });

    if (!valid) {
      console.error('HubSpot signature verification failed');
      return res.status(400).send('Invalid signature');
    }

    // HubSpot delivers an array of events per request
    let events;
    try {
      events = JSON.parse(req.body.toString('utf8'));
    } catch (err) {
      return res.status(400).send('Invalid JSON');
    }
    if (!Array.isArray(events)) events = [events];

    for (const event of events) {
      switch (event.subscriptionType) {
        case 'contact.creation':
          console.log('New contact:', event.objectId);
          // Your code: sync to CRM, trigger welcome workflow, etc.
          break;

        case 'contact.propertyChange':
          console.log('Contact property changed:', event.objectId, event.propertyName, '->', event.propertyValue);
          // Your code: re-sync the changed property downstream
          break;

        case 'contact.deletion':
          console.log('Contact deleted:', event.objectId);
          // Your code: mirror deletion in your system
          break;

        case 'company.creation':
          console.log('New company:', event.objectId);
          break;

        case 'company.propertyChange':
          console.log('Company property changed:', event.objectId, event.propertyName);
          break;

        case 'deal.creation':
          console.log('New deal:', event.objectId);
          break;

        case 'deal.propertyChange':
          console.log('Deal property changed:', event.objectId, event.propertyName, '->', event.propertyValue);
          break;

        case 'ticket.creation':
          console.log('New ticket:', event.objectId);
          break;

        default:
          console.log('Unhandled event:', event.subscriptionType);
      }
    }

    res.status(200).send('OK');
  }
);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = { app, verifyHubSpotWebhook };

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/hubspot`);
  });
}
nextjs/app/webhooks/hubspot/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

const MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes

/**
 * Verify HubSpot v3 webhook signature.
 *
 * signed_content = method + URI + raw body + X-HubSpot-Request-Timestamp
 * signature      = base64(HMAC-SHA256(signed_content, app_client_secret))
 */
export function verifyHubSpotWebhook(args: {
  method: string;
  uri: string;
  rawBody: string;
  timestamp: string | null;
  signature: string | null;
  secret: string;
}): boolean {
  const { method, uri, rawBody, timestamp, signature, secret } = args;
  if (!signature || !timestamp || !secret) return false;

  const ts = Number(timestamp);
  if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > MAX_AGE_MS) return false;

  const signedContent = `${method}${uri}${rawBody}${timestamp}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedContent, 'utf8')
    .digest('base64');

  try {
    return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  } catch {
    return false;
  }
}

interface HubSpotEvent {
  eventId?: number;
  subscriptionId?: number;
  portalId?: number;
  occurredAt?: number;
  subscriptionType?: string;
  objectId?: number;
  propertyName?: string;
  propertyValue?: unknown;
  changeSource?: string;
  changeFlag?: string;
}

export async function POST(request: NextRequest) {
  const rawBody = await request.text();

  const signature = request.headers.get('x-hubspot-signature-v3');
  const timestamp = request.headers.get('x-hubspot-request-timestamp');

  // Reconstruct the URI HubSpot signed. Behind a proxy, NextRequest.url reflects
  // the incoming forwarded URL. Use the forwarded host/proto if present.
  const forwardedHost = request.headers.get('x-forwarded-host');
  const forwardedProto = request.headers.get('x-forwarded-proto');
  const host = forwardedHost ?? request.headers.get('host') ?? new URL(request.url).host;
  const proto = forwardedProto ?? new URL(request.url).protocol.replace(':', '');
  const path = new URL(request.url).pathname + new URL(request.url).search;
  const uri = `${proto}://${host}${path}`;

  const valid = verifyHubSpotWebhook({
    method: request.method,
    uri,
    rawBody,
    timestamp,
    signature,
    secret: process.env.HUBSPOT_CLIENT_SECRET ?? '',
  });

  if (!valid) {
    console.error('HubSpot signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let events: HubSpotEvent[];
  try {
    const parsed = JSON.parse(rawBody);
    events = Array.isArray(parsed) ? parsed : [parsed];
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  for (const event of events) {
    switch (event.subscriptionType) {
      case 'contact.creation':
        console.log('New contact:', event.objectId);
        break;

      case 'contact.propertyChange':
        console.log('Contact property changed:', event.objectId, event.propertyName, '->', event.propertyValue);
        break;

      case 'contact.deletion':
        console.log('Contact deleted:', event.objectId);
        break;

      case 'company.creation':
        console.log('New company:', event.objectId);
        break;

      case 'company.propertyChange':
        console.log('Company property changed:', event.objectId, event.propertyName);
        break;

      case 'deal.creation':
        console.log('New deal:', event.objectId);
        break;

      case 'deal.propertyChange':
        console.log('Deal property changed:', event.objectId, event.propertyName, '->', event.propertyValue);
        break;

      case 'ticket.creation':
        console.log('New ticket:', event.objectId);
        break;

      default:
        console.log('Unhandled event:', event.subscriptionType);
    }
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
import os
import hmac
import hashlib
import base64
import json
import time

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

load_dotenv()

app = FastAPI()

hubspot_client_secret = os.environ.get("HUBSPOT_CLIENT_SECRET", "")

MAX_AGE_MS = 5 * 60 * 1000  # 5 minutes


def verify_hubspot_webhook(
    method: str,
    uri: str,
    raw_body: bytes,
    timestamp: str,
    signature: str,
    secret: str,
) -> bool:
    """Verify a HubSpot v3 webhook signature.

    signed_content = method + uri + raw_body + timestamp
    signature      = base64(HMAC-SHA256(signed_content, app_client_secret))
    """
    if not signature or not timestamp or not secret:
        return False

    try:
        ts = int(timestamp)
    except (TypeError, ValueError):
        return False

    if abs(int(time.time() * 1000) - ts) > MAX_AGE_MS:
        return False

    body = raw_body.decode("utf-8")
    signed_content = f"{method}{uri}{body}{timestamp}"

    expected = base64.b64encode(
        hmac.new(
            secret.encode("utf-8"),
            signed_content.encode("utf-8"),
            hashlib.sha256,
        ).digest()
    ).decode("utf-8")

    return hmac.compare_digest(expected, signature)


def _request_uri(request: Request) -> str:
    """Reconstruct the URI HubSpot signed, honoring X-Forwarded-* when present."""
    forwarded_host = request.headers.get("x-forwarded-host")
    forwarded_proto = request.headers.get("x-forwarded-proto")
    host = forwarded_host or request.headers.get("host") or request.url.netloc
    proto = forwarded_proto or request.url.scheme
    path = request.url.path
    query = request.url.query
    if query:
        return f"{proto}://{host}{path}?{query}"
    return f"{proto}://{host}{path}"


@app.post("/webhooks/hubspot")
async def hubspot_webhook(request: Request):
    raw_body = await request.body()
    signature = request.headers.get("x-hubspot-signature-v3")
    timestamp = request.headers.get("x-hubspot-request-timestamp")
    uri = _request_uri(request)

    if not verify_hubspot_webhook(
        method=request.method,
        uri=uri,
        raw_body=raw_body,
        timestamp=timestamp or "",
        signature=signature or "",
        secret=hubspot_client_secret,
    ):
        raise HTTPException(status_code=400, detail="Invalid signature")

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

    events = parsed if isinstance(parsed, list) else [parsed]

    for event in events:
        subscription_type = event.get("subscriptionType")

        if subscription_type == "contact.creation":
            print(f"New contact: {event.get('objectId')}")
            # Your code: sync to CRM, trigger welcome workflow, etc.

        elif subscription_type == "contact.propertyChange":
            print(
                "Contact property changed:",
                event.get("objectId"),
                event.get("propertyName"),
                "->",
                event.get("propertyValue"),
            )

        elif subscription_type == "contact.deletion":
            print(f"Contact deleted: {event.get('objectId')}")

        elif subscription_type == "company.creation":
            print(f"New company: {event.get('objectId')}")

        elif subscription_type == "company.propertyChange":
            print(
                "Company property changed:",
                event.get("objectId"),
                event.get("propertyName"),
            )

        elif subscription_type == "deal.creation":
            print(f"New deal: {event.get('objectId')}")

        elif subscription_type == "deal.propertyChange":
            print(
                "Deal property changed:",
                event.get("objectId"),
                event.get("propertyName"),
                "->",
                event.get("propertyValue"),
            )

        elif subscription_type == "ticket.creation":
            print(f"New ticket: {event.get('objectId')}")

        else:
            print(f"Unhandled event: {subscription_type}")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=3000)

From hookdeck/webhook-skills ↗

Or install the HubSpot webhooks skill:

npx skills add hookdeck/webhook-skills --skill hubspot-webhooks

Common failures

URI doesn't match what HubSpot called

The URI is signed in full, including the scheme, host and query. Behind a proxy, rebuild the public URL rather than the one your app sees, and decode the characters HubSpot lists, which its code examples do in the query string only.

Body parsed before verification

Sign the body as it arrived. Re-serializing parsed JSON can change the bytes and break the match.

Timestamp read as seconds

X-HubSpot-Request-Timestamp is in milliseconds. Compare it with the current time in milliseconds, and append it to the signed string unchanged.

Wrong header or key

X-HubSpot-Signature is a plain SHA-256 hex digest, and X-HubSpot-Signature-v3 is a base64 HMAC. Both use your app's client secret, not an access token.

From Hookdeck's HubSpot guide

Let Event Gateway verify HubSpot signatures.

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

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