Verify Notion webhooks
Notion signs each event so you can confirm that it came from Notion and wasn't changed. The X-Notion-Signature header holds sha256= and a hex HMAC-SHA256 of the raw body, keyed with the verification_token Notion sends once when you create the subscription. verifyWebhookSignature() in @notionhq/client makes the check for you.
These pages cover connection webhooks, which a connection subscribes to and Notion signs. The Send webhook action in buttons and database automations is a separate no-code feature: it POSTs the properties you pick to a URL, and Notion documents no signature for it.
The facts
{raw body} The request body exactly as sent, with nothing added. No timestamp is added to the signed content.
Save the verification_token from the first POST, then recompute a digest over the raw body and compare Notion webhook secret
The signing key is the verification_token Notion POSTs to your URL when you create the subscription. You paste the same value into Notion to activate the subscription. Keep it in an environment variable, not in source code.
- Where it comes from: the one-time POST to your webhook URL, as
verification_tokenin the JSON body. Notion's docs show no other place to read it, so store it when it arrives. - If it doesn't arrive: click Resend token in the verification dialog in the connection's Webhooks tab.
- Format: Notion's example starts with
secret_. Treat the rest as an opaque string. - Scope: each subscription has its own. It isn't the token your connection uses for API calls.
- Rotation: Notion's docs say to update your stored token if you rotate or recreate the subscription, and they describe no overlap between old and new.
Source: Notion docs ↗
Code
Docs discrepancy · read before the code
Notion's sample code hashes JSON.stringify(body) over a parsed body, while the same page's SDK note says re-serialized JSON fails verification. The sample only works when serialization reproduces the bytes. Hash the raw body.
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify a Notion webhook signature.
*
* Notion sends `X-Notion-Signature: sha256=<hex>` where the hex is the
* HMAC-SHA256 of the raw request body, keyed with the verification_token
* captured during the one-time handshake.
*/
function verifyNotionSignature(rawBody, signatureHeader, verificationToken) {
if (!signatureHeader || !verificationToken) return false;
const expected = `sha256=${crypto
.createHmac('sha256', verificationToken)
.update(rawBody)
.digest('hex')}`;
try {
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signatureHeader)
);
} catch {
return false;
}
}
// Notion requires the raw body for HMAC verification
app.post('/webhooks/notion',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-notion-signature'];
const token = process.env.NOTION_VERIFICATION_TOKEN;
// Handshake: the first delivery to a new subscription has no signature
// and the body is { "verification_token": "secret_..." }. Surface it so
// the developer can paste it into the Notion UI to activate the
// subscription.
if (!signature) {
try {
const parsed = JSON.parse(req.body.toString('utf8'));
if (parsed && typeof parsed.verification_token === 'string') {
console.log(
'Notion verification_token (paste this into the Notion UI):',
parsed.verification_token
);
return res.status(200).json({ received: true });
}
} catch {
// fall through to 400
}
return res.status(400).send('Missing X-Notion-Signature');
}
if (!verifyNotionSignature(req.body, signature, token)) {
console.error('Notion signature verification failed');
return res.status(401).send('Invalid signature');
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON body');
}
console.log(`Received ${event.type} (id: ${event.id})`);
switch (event.type) {
case 'page.content_updated':
console.log('Page content updated:', event.entity?.id);
// Your code: re-index the page, sync content, etc.
break;
case 'page.properties_updated':
console.log('Page properties updated:', event.entity?.id);
// Your code: react to status changes, recompute derived fields, etc.
break;
case 'page.created':
console.log('Page created:', event.entity?.id);
// Your code: provision related resources, notify, etc.
break;
case 'page.deleted':
console.log('Page deleted:', event.entity?.id);
// Your code: clean up mirrors, audit log, etc.
break;
case 'page.locked':
console.log('Page locked:', event.entity?.id);
// Your code: publishing / compliance flow
break;
case 'page.moved':
console.log('Page moved:', event.entity?.id);
// Your code: re-evaluate access, rebuild paths
break;
case 'comment.created':
console.log('Comment created:', event.entity?.id);
// Your code: notify, run AI triage, etc.
break;
case 'data_source.schema_updated':
console.log('Data source schema updated:', event.entity?.id);
// Your code: re-derive types
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
res.json({ received: true });
}
);
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyNotionSignature = verifyNotionSignature;
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/notion`);
});
} import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify a Notion webhook signature.
*
* Notion sends `X-Notion-Signature: sha256=<hex>` where the hex is the
* HMAC-SHA256 of the raw request body, keyed with the verification_token
* captured during the one-time handshake.
*/
export function verifyNotionSignature(
rawBody: string,
signatureHeader: string | null,
verificationToken: string | undefined
): boolean {
if (!signatureHeader || !verificationToken) return false;
const expected = `sha256=${crypto
.createHmac('sha256', verificationToken)
.update(rawBody)
.digest('hex')}`;
try {
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signatureHeader)
);
} catch {
return false;
}
}
export async function POST(request: NextRequest) {
// Use raw text — re-serialising parsed JSON would change the bytes Notion
// signed and break verification.
const rawBody = await request.text();
const signature = request.headers.get('x-notion-signature');
const token = process.env.NOTION_VERIFICATION_TOKEN;
// Handshake: the first delivery to a new subscription has no signature and
// the body is { "verification_token": "secret_..." }. Surface it so the
// developer can paste it into the Notion UI.
if (!signature) {
try {
const parsed = JSON.parse(rawBody);
if (parsed && typeof parsed.verification_token === 'string') {
console.log(
'Notion verification_token (paste this into the Notion UI):',
parsed.verification_token
);
return NextResponse.json({ received: true });
}
} catch {
// fall through to 400
}
return NextResponse.json(
{ error: 'Missing X-Notion-Signature' },
{ status: 400 }
);
}
if (!verifyNotionSignature(rawBody, signature, token)) {
console.error('Notion signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
let event: {
id?: string;
type?: string;
entity?: { id?: string; type?: string };
};
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
console.log(`Received ${event.type} (id: ${event.id})`);
switch (event.type) {
case 'page.content_updated':
console.log('Page content updated:', event.entity?.id);
// Your code: re-index the page, sync content, etc.
break;
case 'page.properties_updated':
console.log('Page properties updated:', event.entity?.id);
// Your code: react to status changes, recompute derived fields, etc.
break;
case 'page.created':
console.log('Page created:', event.entity?.id);
break;
case 'page.deleted':
console.log('Page deleted:', event.entity?.id);
break;
case 'page.locked':
console.log('Page locked:', event.entity?.id);
break;
case 'page.moved':
console.log('Page moved:', event.entity?.id);
break;
case 'comment.created':
console.log('Comment created:', event.entity?.id);
break;
case 'data_source.schema_updated':
console.log('Data source schema updated:', event.entity?.id);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
return NextResponse.json({ received: true });
} 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_notion_signature(
raw_body: bytes, signature_header: str | None, verification_token: str | None
) -> bool:
"""Verify a Notion webhook signature.
Notion sends ``X-Notion-Signature: sha256=<hex>`` where the hex is the
HMAC-SHA256 of the raw request body, keyed with the verification_token
captured during the one-time handshake.
"""
if not signature_header or not verification_token:
return False
expected = "sha256=" + hmac.new(
verification_token.encode("utf-8"), raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature_header)
@app.post("/webhooks/notion")
async def notion_webhook(request: Request):
raw_body = await request.body()
signature = request.headers.get("x-notion-signature")
token = os.environ.get("NOTION_VERIFICATION_TOKEN")
# Handshake: the first delivery to a new subscription has no signature
# and the body is { "verification_token": "secret_..." }. Surface it so
# the developer can paste it into the Notion UI to activate the
# subscription.
if not signature:
try:
data = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON body")
if isinstance(data, dict) and isinstance(data.get("verification_token"), str):
print(
"Notion verification_token (paste this into the Notion UI):",
data["verification_token"],
)
return {"received": True}
raise HTTPException(status_code=400, detail="Missing X-Notion-Signature")
if not verify_notion_signature(raw_body, signature, token):
raise HTTPException(status_code=401, detail="Invalid signature")
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON body")
event_type = event.get("type")
entity_id = (event.get("entity") or {}).get("id")
print(f"Received {event_type} (id: {event.get('id')})")
if event_type == "page.content_updated":
print("Page content updated:", entity_id)
# Your code: re-index the page, sync content, etc.
elif event_type == "page.properties_updated":
print("Page properties updated:", entity_id)
# Your code: react to status changes, recompute derived fields, etc.
elif event_type == "page.created":
print("Page created:", entity_id)
elif event_type == "page.deleted":
print("Page deleted:", entity_id)
elif event_type == "page.locked":
print("Page locked:", entity_id)
elif event_type == "page.moved":
print("Page moved:", entity_id)
elif event_type == "comment.created":
print("Comment created:", entity_id)
elif event_type == "data_source.schema_updated":
print("Data source schema updated:", entity_id)
else:
print(f"Unhandled event type: {event_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) Or install the Notion webhooks skill:
npx skills add hookdeck/webhook-skills --skill notion-webhooks
Common failures
Body parsed before verification
Notion signs the bytes it sent, and re-serialized JSON can differ. Notion's sample code hashes JSON.stringify(body), so don't copy that part: capture the raw body before any parser runs.
Wrong key
The key is the subscription's verification_token, not the token your connection uses for API calls. Recreating a subscription means updating the token you've stored.
Comparing without the prefix
The header value starts with sha256=, so compare it with sha256= plus your hex digest, or strip the prefix first.
Checking the setup request
The first POST delivers the token you'd need to check it, so it can't be verified. Handle a body with verification_token and no type before your signature check, and log the token for someone to copy rather than storing it automatically.
Let Event Gateway verify Notion signatures.
Event Gateway verifies the signature on each Notion delivery before it reaches your service, then queues it and retries failures on your schedule.