# Verify Bitbucket webhooks

Bitbucket Cloud signs a delivery when the webhook has a secret, so you can confirm that it came from Bitbucket and wasn't changed on the way. The `X-Hub-Signature` header holds `sha256=` followed by an HMAC-SHA256 hex digest of the raw body, keyed with that secret. With no secret set, Bitbucket sends no signature, and Atlassian only announced secrets in October 2023, so check your older webhooks.

These pages cover Bitbucket Cloud. Bitbucket Data Center is a separate self-managed product, with its own event keys, such as `repo:refs_changed`, and [its own webhook docs](https://confluence.atlassian.com/bitbucketserver/manage-webhooks-938025878.html).

Agent skill: `npx skills add hookdeck/webhook-skills --skill bitbucket-webhooks` ([details](https://hookdeck.com/webhooks/bitbucket/skill))

> Independent reference generated from hookdeck/webhook-registry (commit a24c8d9, 19 Nov 2026). [Bitbucket's official docs](https://support.atlassian.com/bitbucket-cloud/docs/event-payloads/).

[Overview](https://hookdeck.com/webhooks/bitbucket) · [Webhook events (29)](https://hookdeck.com/webhooks/bitbucket/events) · [MCP events](https://hookdeck.com/webhooks/bitbucket/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/bitbucket/verify) · [Production guide](https://hookdeck.com/webhooks/bitbucket/guide-duplicates-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/bitbucket/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `X-Hub-Signature` Not every delivery is signed: check your setup. | [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/) |
| Scheme | `HMAC-SHA256` | [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/) |
| Signed material | `{raw body}` The request body exactly as sent, with no timestamp or other data added. | [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/) |
| What to build | `Recompute a digest over the raw body and compare` | [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/) |
| Key | `shared secret` | [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/) |

## Bitbucket webhook secret

Each webhook has its own secret, which you type or have Bitbucket generate when you create or edit the webhook. It isn't an API token, and you can't read it back after saving. Keep it in an environment variable, not in source code.

- Where: the Secret field on the Add new webhook page, under Webhooks in the repository settings. Edit an existing webhook to add one.
- Generate secret: this button creates one for you. If you write your own, use a random string with high entropy.
- Format: Bitbucket sets no prefix. The REST API accepts up to 128 characters in the `secret` field.
- After saving: the secret can't be viewed or retrieved, in the UI or the API. The API's `secret_set` field only says whether the webhook has one.
- Changing it: edit the webhook and update everything that uses the old value. The docs describe no period when both secrets work.
- Remove it: in the REST API, set `secret` to `null` or an empty string. The webhook then stops sending a signature.

Source: [Bitbucket docs](https://support.atlassian.com/bitbucket-cloud/docs/manage-webhooks/)

## Code

### Express

From [webhook-skills: skills/bitbucket-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/bitbucket-webhooks/examples/express/src/index.js)

```javascript
// Generated with: bitbucket-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify Bitbucket webhook signature
 * @param {Buffer} rawBody - Raw request body
 * @param {string} signatureHeader - X-Hub-Signature header value (format: sha256=<hex>)
 * @param {string} secret - Bitbucket webhook secret
 * @returns {boolean} - Whether signature is valid
 */
function verifyBitbucketWebhook(rawBody, signatureHeader, secret) {
  if (!signatureHeader) {
    return false;
  }

  // Header format: sha256=<hex>. Split on "=" to separate method and signature.
  const [algo, signature] = signatureHeader.split('=');
  if (algo !== 'sha256' || !signature) {
    return false;
  }

  // Compute expected signature over the raw body
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // Use timing-safe comparison to prevent timing attacks
  try {
    return crypto.timingSafeEqual(
      Buffer.from(signature, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    return false;
  }
}

// Bitbucket webhook endpoint - must use raw body for signature verification
app.post('/webhooks/bitbucket',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature = req.headers['x-hub-signature'];
    const event = req.headers['x-event-key'];
    const requestUuid = req.headers['x-request-uuid'];

    // Verify webhook signature
    if (!verifyBitbucketWebhook(req.body, signature, process.env.BITBUCKET_WEBHOOK_SECRET)) {
      console.error('Webhook signature verification failed');
      return res.status(401).send('Invalid signature');
    }

    // Parse the payload after verification
    const payload = JSON.parse(req.body.toString());

    console.log(`Received ${event} event (uuid: ${requestUuid})`);

    // Handle the event based on the X-Event-Key
    switch (event) {
      case 'repo:push': {
        const change = payload.push?.changes?.[0];
        const name = change?.new?.name || change?.old?.name;
        console.log(`Push to ${name}:`, change?.commits?.[0]?.message);
        // Your code: Trigger CI/CD, run tests, deploy, etc.
        break;
      }

      case 'pullrequest:created':
        console.log(`PR #${payload.pullrequest.id} created:`, payload.pullrequest.title);
        // Your code: Assign reviewers, run checks, etc.
        break;

      case 'pullrequest:updated':
        console.log(`PR #${payload.pullrequest.id} updated:`, payload.pullrequest.title);
        // Your code: Re-run checks, notify reviewers, etc.
        break;

      case 'pullrequest:approved':
        console.log(`PR #${payload.pullrequest.id} approved by ${payload.approval?.user?.display_name}`);
        // Your code: Merge gating, notifications, etc.
        break;

      case 'pullrequest:fulfilled':
        console.log(`PR #${payload.pullrequest.id} merged:`, payload.pullrequest.title);
        // Your code: Deploy, notify, close linked issues, etc.
        break;

      case 'pullrequest:rejected':
        console.log(`PR #${payload.pullrequest.id} declined:`, payload.pullrequest.title);
        // Your code: Cleanup, notify author, etc.
        break;

      case 'pullrequest:comment_created':
        console.log(`Comment on PR #${payload.pullrequest.id}:`, payload.comment?.content?.raw);
        // Your code: Bot responses, command parsing, etc.
        break;

      case 'issue:created':
        console.log(`Issue #${payload.issue.id} created:`, payload.issue.title);
        // Your code: Triage, label, notify, etc.
        break;

      default:
        console.log(`Unhandled event: ${event}`);
    }

    // Return 200 to acknowledge receipt
    res.status(200).send('OK');
  }
);

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

// Export app for testing
module.exports = { app, verifyBitbucketWebhook };

// 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/bitbucket`);
  });
}
```

### Next.js

From [webhook-skills: skills/bitbucket-webhooks/examples/nextjs/app/webhooks/bitbucket/route.ts](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/bitbucket-webhooks/examples/nextjs/app/webhooks/bitbucket/route.ts)

```typescript
// Generated with: bitbucket-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

/**
 * Verify Bitbucket webhook signature.
 * Header format: sha256=<hex>. HMAC-SHA256 hex over the raw body.
 */
export function verifyBitbucketWebhook(
  rawBody: string,
  signatureHeader: string | null,
  secret: string
): boolean {
  if (!signatureHeader) {
    return false;
  }

  // Split on "=" to separate method and signature.
  const [algo, signature] = signatureHeader.split('=');
  if (algo !== 'sha256' || !signature) {
    return false;
  }

  // Compute expected signature over the raw body
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // Use timing-safe comparison to prevent timing attacks
  try {
    return crypto.timingSafeEqual(
      Buffer.from(signature, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  // Get the raw body for signature verification
  const body = await request.text();
  const signature = request.headers.get('x-hub-signature');
  const event = request.headers.get('x-event-key');
  const requestUuid = request.headers.get('x-request-uuid');

  // Verify webhook signature
  if (!verifyBitbucketWebhook(body, signature, process.env.BITBUCKET_WEBHOOK_SECRET!)) {
    console.error('Webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  // Parse the payload after verification
  const payload = JSON.parse(body);

  console.log(`Received ${event} event (uuid: ${requestUuid})`);

  // Handle the event based on the X-Event-Key
  switch (event) {
    case 'repo:push': {
      const change = payload.push?.changes?.[0];
      const name = change?.new?.name || change?.old?.name;
      console.log(`Push to ${name}:`, change?.commits?.[0]?.message);
      // Your code: Trigger CI/CD, run tests, deploy, etc.
      break;
    }

    case 'pullrequest:created':
      console.log(`PR #${payload.pullrequest.id} created:`, payload.pullrequest.title);
      // Your code: Assign reviewers, run checks, etc.
      break;

    case 'pullrequest:updated':
      console.log(`PR #${payload.pullrequest.id} updated:`, payload.pullrequest.title);
      // Your code: Re-run checks, notify reviewers, etc.
      break;

    case 'pullrequest:approved':
      console.log(`PR #${payload.pullrequest.id} approved by ${payload.approval?.user?.display_name}`);
      // Your code: Merge gating, notifications, etc.
      break;

    case 'pullrequest:fulfilled':
      console.log(`PR #${payload.pullrequest.id} merged:`, payload.pullrequest.title);
      // Your code: Deploy, notify, close linked issues, etc.
      break;

    case 'pullrequest:rejected':
      console.log(`PR #${payload.pullrequest.id} declined:`, payload.pullrequest.title);
      // Your code: Cleanup, notify author, etc.
      break;

    case 'pullrequest:comment_created':
      console.log(`Comment on PR #${payload.pullrequest.id}:`, payload.comment?.content?.raw);
      // Your code: Bot responses, command parsing, etc.
      break;

    case 'issue:created':
      console.log(`Issue #${payload.issue.id} created:`, payload.issue.title);
      // Your code: Triage, label, notify, etc.
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }

  // Return 200 to acknowledge receipt
  return NextResponse.json({ received: true });
}
```

### FastAPI

From [webhook-skills: skills/bitbucket-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/bitbucket-webhooks/examples/fastapi/main.py)

```python
# Generated with: bitbucket-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import hmac
import hashlib
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException

load_dotenv()

app = FastAPI()

bitbucket_secret = os.environ.get("BITBUCKET_WEBHOOK_SECRET")


def verify_bitbucket_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
    """Verify Bitbucket webhook signature.

    Header format: sha256=<hex>. HMAC-SHA256 hex over the raw body.
    """
    if not signature_header:
        return False

    # Partition on "=" to separate method and signature.
    algo, _, signature = signature_header.partition("=")
    if algo != "sha256" or not signature:
        return False

    # Compute expected signature over the raw body
    expected_signature = hmac.new(
        secret.encode("utf-8"),
        raw_body,
        hashlib.sha256
    ).hexdigest()

    # Use timing-safe comparison
    return hmac.compare_digest(signature, expected_signature)


@app.post("/webhooks/bitbucket")
async def bitbucket_webhook(request: Request):
    # Get the raw body for signature verification
    raw_body = await request.body()
    signature_header = request.headers.get("x-hub-signature")
    event = request.headers.get("x-event-key")
    request_uuid = request.headers.get("x-request-uuid")

    # Verify webhook signature
    if not verify_bitbucket_webhook(raw_body, signature_header, bitbucket_secret):
        raise HTTPException(status_code=401, detail="Invalid signature")

    # Parse the payload after verification
    payload = json.loads(raw_body)

    print(f"Received {event} event (uuid: {request_uuid})")

    # Handle the event based on the X-Event-Key
    if event == "repo:push":
        changes = payload.get("push", {}).get("changes", [])
        change = changes[0] if changes else {}
        name = (change.get("new") or change.get("old") or {}).get("name")
        commits = change.get("commits", [])
        message = commits[0].get("message") if commits else None
        print(f"Push to {name}: {message}")
        # Your code: Trigger CI/CD, run tests, deploy, etc.

    elif event == "pullrequest:created":
        pr = payload["pullrequest"]
        print(f"PR #{pr['id']} created: {pr['title']}")
        # Your code: Assign reviewers, run checks, etc.

    elif event == "pullrequest:updated":
        pr = payload["pullrequest"]
        print(f"PR #{pr['id']} updated: {pr['title']}")
        # Your code: Re-run checks, notify reviewers, etc.

    elif event == "pullrequest:approved":
        pr = payload["pullrequest"]
        approval = payload.get("approval", {})
        user = approval.get("user", {})
        print(f"PR #{pr['id']} approved by {user.get('display_name')}")
        # Your code: Merge gating, notifications, etc.

    elif event == "pullrequest:fulfilled":
        pr = payload["pullrequest"]
        print(f"PR #{pr['id']} merged: {pr['title']}")
        # Your code: Deploy, notify, close linked issues, etc.

    elif event == "pullrequest:rejected":
        pr = payload["pullrequest"]
        print(f"PR #{pr['id']} declined: {pr['title']}")
        # Your code: Cleanup, notify author, etc.

    elif event == "pullrequest:comment_created":
        pr = payload["pullrequest"]
        comment = payload.get("comment", {}).get("content", {}).get("raw")
        print(f"Comment on PR #{pr['id']}: {comment}")
        # Your code: Bot responses, command parsing, etc.

    elif event == "issue:created":
        issue = payload["issue"]
        print(f"Issue #{issue['id']} created: {issue['title']}")
        # Your code: Triage, label, notify, etc.

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

    # Return 200 to acknowledge receipt
    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=8000)
```

Or install the Bitbucket webhooks skill: `npx skills add hookdeck/webhook-skills --skill bitbucket-webhooks`

## Common failures

- **No secret on the webhook.** Bitbucket only sends X-Hub-Signature when the webhook has a secret. If the header is missing, edit the webhook and add one. Webhooks that predate secrets may have none.
- **Body changed before verification.** Bitbucket signs the payload verbatim, so formatting it first gives a different signature. Verify the raw bytes as they arrived, before a body parser re-serializes them, and handle them as UTF-8.
- **Secret out of date.** A saved secret can't be viewed or retrieved, so you can't compare it with what your server holds. If you're unsure, set a new one and update your server to match.
- **Hash method hardcoded.** The value starts with its hash method. Bitbucket uses sha256 today and says this might change, and code that assumes sha256 would then start failing.

From [Hookdeck's Bitbucket guide](https://hookdeck.com/webhooks/bitbucket/guide-duplicates-retries-timeouts).

---

Not affiliated with Bitbucket. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/bitbucket.json) · [Report a correction](https://hookdeck.com/contact)
