Database webhooks
When a row changes, Naijacloud sends an HTTP request to your URL with the old and new row. Requests are signed, retried for about a day, and sent from outside your database. Postgres only.
Create a webhook
Open the Postgres database and choose the Webhooks tab, then Create webhook. Give it:
- a name, for you,
- the schema (
publicunless you use another) and the table whose rows fire it, - the events: any of
INSERT,UPDATEandDELETE, - the method (
POSTorGET) and the URL, which must behttps://, - any extra HTTP headers your receiver checks, such as an
Authorizationtoken, - a timeout: how long to wait for your URL to answer, from 1,000 to 30,000 ms. The default is 10,000 ms.
When you create it, the dashboard shows the webhook's signing secret once. Copy it into your receiver's settings before you close the dialog; you can't see it again, only rotate it.
The table and schema can't be changed after the webhook is created. To watch another table, create another webhook. A database can have up to 20 webhooks.
How it works
Creating a webhook adds an ordinary Postgres trigger to the table:
create trigger "orders_webhook"
after insert or update or delete on public.orders
for each row
execute function naijacloud.http_request(
'https://example.com/hooks/orders', -- url
'POST', -- method
'{"Content-Type":"application/json"}', -- headers, as JSON
'{}', -- params, as JSON
'10000' -- timeout in ms
);naijacloud.http_request(url, method, headers_json, params_json, timeout_ms)
does not make a request itself. It inserts one row into a queue table,
naijacloud_hooks.outbox, inside the same transaction as your write. That has
two consequences:
- A rolled-back write never sends. The queued row rolls back with it.
- Your database never makes HTTP calls. Naijacloud's worker reads the queue every few seconds and sends the requests from outside the database, so a slow or unreachable receiver never slows your queries down.
Coming from Supabase
The same function also exists as supabase_functions.http_request(...), with
the same five arguments, and the request body has the same shape as Supabase's.
A trigger copied from a Supabase project, or restored from a Supabase dump,
works unchanged:
create trigger "track_purchased"
after insert on public.purchases
for each row
execute function supabase_functions.http_request(
'https://example.com/hooks/purchase',
'POST',
'{"Content-Type":"application/json"}',
'{}',
'5000'
);Triggers like this are picked up and listed on the Webhooks tab, marked Found in database, on their first event, when you set up a webhook on the database, or when you choose Find triggers in database on the tab. From then on they have a signing secret, a delivery log and retries like any other webhook. A found webhook's first secret is never shown: choose Rotate secret on it to get one you can verify with.
Raw pg_net (net.http_post, net.http_get) is not available. Use
naijacloud.http_request, or the supabase_functions.http_request name,
instead.
The request
A POST webhook sends a JSON body:
{
"type": "INSERT",
"table": "orders",
"schema": "public",
"record": { "id": 42, "status": "paid", "total": 125000 },
"old_record": null
}typeisINSERT,UPDATEorDELETE.recordis the row after the change. It isnullonDELETE.old_recordis the row before the change. It isnullonINSERT.- A test event, from Send test event, has
"type": "TEST"andnullfor both records. - A row larger than 256 KB is sent with
recordandold_recordreplaced by{"_truncated": true, "_bytes": N}, whereNis the row's size. Read the row from the database if you need all of it.
A GET webhook sends no body. The trigger's params become the URL's query
string.
Every request carries these headers, plus any you added:
| Header | Value |
|---|---|
webhook-id | The event's ID. The same on every retry and redelivery. |
webhook-timestamp | When this attempt was sent, in Unix seconds. |
webhook-signature | v1,<signature>, explained below. |
content-type | application/json, unless you set your own. |
user-agent | Naijacloud-Database-Webhooks/1 |
Your own headers can't override the webhook-* headers, host or
content-length. Custom header values are stored encrypted.
Verify the signature
Requests are signed the Standard Webhooks way, so you can check that one really came from Naijacloud and was not changed on the way.
The signature is an HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body>,
keyed with your secret: the part of the whsec_... value after whsec_,
base64-decoded. It is sent base64-encoded as v1,<signature>. While a secret is
being rotated, two signatures are sent, separated by a space; accept the request
if either one matches.
Three rules for every receiver:
- Verify against the raw body bytes, exactly as they arrived. Parsing the JSON and serialising it again changes the bytes and the signature won't match.
- Reject requests older than 5 minutes, by
webhook-timestamp, so a recorded request can't be replayed later. - Drop duplicates by
webhook-id. Delivery is at least once, so the same event can arrive more than once.
The standardwebhooks libraries check the signature and the 5-minute window
for you. You still hand them the raw body, and drop duplicates yourself.
Node.js
npm install standardwebhooksimport express from 'express';
import { Webhook } from 'standardwebhooks';
const wh = new Webhook(process.env.WEBHOOK_SECRET!); // whsec_...
const app = express();
// express.raw keeps the body as the exact bytes that were signed.
app.post('/hooks/orders', express.raw({ type: '*/*' }), (req, res) => {
let event;
try {
event = wh.verify(req.body.toString('utf8'), req.headers as Record<string, string>);
} catch {
return res.status(401).send('bad signature');
}
// event.type, event.record, event.old_record
res.sendStatus(204);
});Python
pip install standardwebhooksimport os
from flask import Flask, request
from standardwebhooks.webhooks import Webhook
wh = Webhook(os.environ["WEBHOOK_SECRET"]) # whsec_...
app = Flask(__name__)
@app.post("/hooks/orders")
def orders():
try:
event = wh.verify(request.get_data(), dict(request.headers))
except Exception:
return "bad signature", 401
# event["type"], event["record"], event["old_record"]
return "", 204PHP
composer require standard-webhooks/standard-webhooks<?php
require 'vendor/autoload.php';
$wh = new \StandardWebhooks\Webhook(getenv('WEBHOOK_SECRET')); // whsec_...
$payload = file_get_contents('php://input');
$headers = [
'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
];
try {
$event = $wh->verify($payload, $headers);
} catch (Exception $e) {
http_response_code(401);
exit('bad signature');
}
// $event['type'], $event['record'], $event['old_record']
http_response_code(204);Go
go get github.com/standard-webhooks/standard-webhooks/libraries/gopackage main
import (
"io"
"net/http"
"os"
standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)
func main() {
wh, err := standardwebhooks.NewWebhook(os.Getenv("WEBHOOK_SECRET")) // whsec_...
if err != nil {
panic(err)
}
http.HandleFunc("/hooks/orders", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "unreadable body", http.StatusBadRequest)
return
}
if err := wh.Verify(body, r.Header); err != nil {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
// json.Unmarshal(body, &event)
w.WriteHeader(http.StatusNoContent)
})
http.ListenAndServe(":8080", nil)
}Without a library
The check is short enough to write yourself. In Node.js, with crypto:
import { createHmac, timingSafeEqual } from 'node:crypto';
/** `rawBody` is the request body exactly as received. */
export function verifyWebhook(
secret: string, // whsec_...
headers: Record<string, string | undefined>,
rawBody: string
): boolean {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !timestamp || !signatures) return false;
// Older (or further in the future) than 5 minutes: refuse.
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = createHmac('sha256', key)
.update(`${id}.${timestamp}.${rawBody}`)
.digest();
// During a rotation there are two, separated by a space.
return signatures.split(' ').some((entry) => {
const [version, signature] = entry.split(',');
if (version !== 'v1' || !signature) return false;
const given = Buffer.from(signature, 'base64');
return given.length === expected.length && timingSafeEqual(given, expected);
});
}Rotating the secret
Rotate secret on the webhook makes a new secret and shows it once. The old secret keeps signing for 24 hours alongside the new one, so you have a day to put the new one in your receiver. After that only the new secret signs.
Delivery and retries
Delivery is at least once. Any 2xx response counts as delivered.
A delivery is retried after a timeout, a connection error, or a 408, 429 or
5xx response. Any other 4xx, and any 3xx, is not retried: redirects are
never followed, so point the webhook at the final URL.
Each event gets up to 7 attempts: one straight away, then after 30 seconds, 2 minutes, 10 minutes, 1 hour, 6 hours and 16 hours. That is about 24 hours in all. If the last attempt fails too, the event is marked Failed.
Each attempt waits for the webhook's timeout: 10 seconds unless you set it between 1 and 30 seconds.
Auto-pause
If every delivery to a webhook fails for 24 hours with no success in between, Naijacloud pauses it: its trigger is turned off and workspace owners and admins get an email.
To recover, fix the receiver, then open the webhook and choose Resume. Use Redeliver on the events you still need.
Changes that happen while a webhook is paused, by you or automatically, are recorded in the log as Skipped and are not sent. You can redeliver them after you resume.
The delivery log
Each webhook has a delivery log listing every event: what fired it, its status (Pending, Delivered, Failed or Skipped), how many attempts it took and the last status code. Filter it by status.
Open an event to see the request that was sent, its webhook-id, and every
attempt with its status code, the first 2 KB of the response body and how long
it took. From there:
- Redeliver sends the event again, under the same
webhook-id. - Send test event, on the webhook, sends a
TESTevent so you can check your receiver without changing a row.
The log is kept for 7 days on Free databases and 30 days on paid ones.
Security
- URLs must use
https://. - Private, loopback, link-local (including cloud metadata addresses), CGNAT and tailnet addresses, and other internal ranges, are refused. The check is made after DNS resolution, on every attempt, so a hostname can't be pointed at an internal address later.
- Custom header values are stored encrypted.
- Up to 20 webhooks per database. Custom headers can't override
webhook-*,hostorcontent-length.