Receive webhooks
Sometimes the data flows the other way: a shop system changes the price of a product, and the product page should show the new price. Tenon has no built-in route for incoming webhooks. Pick the way that fits the sender:
| The sender | Use |
|---|---|
| Can call an API with a header, like n8n, Zapier or your own script | An API key. No code in Tenon. |
| Sends its own webhook format to a URL, like most shop systems | A webhook route in a plugin. |
Use an API key
Create an API key with update on the collection, for example collection:products. The sender then calls the HTTP API with the key in the x-api-key header. The key may change only what its permissions allow, and every write is validated like a write from the admin.
Add a webhook route
A plugin can add a public route under /_tenon/<plugin name>. The route checks the request and queues a job. The job writes the change:
import { definePlugin, defineTask } from "tenoncms";
export const shop = definePlugin({
name: "shop",
publicRoutes: (api) =>
api.post("/webhook", async (c) => {
const body = await c.req.text();
if (!(await isSignedByShop(body, c.req.header("x-shop-signature")))) {
return c.body(null, 401);
}
const { sku, price } = JSON.parse(body);
await c.var.cms.jobs.queue("shop:update-price", { sku, price });
return c.body(null, 202);
}),
jobs: {
tasks: {
"shop:update-price": defineTask({
run: async ({ payload, cms }) => {
const { sku, price } = payload as { sku: string; price: number };
const product = await cms.findOne("products", { where: { sku } });
if (!product) return "unknown sku";
await cms.update("products", product.id, { price });
return "updated";
},
}),
},
},
});
async function isSignedByShop(body: string, signature: string | undefined) {
if (!signature) return false;
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(process.env.SHOP_WEBHOOK_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"],
);
try {
const expected = Uint8Array.from(atob(signature), (char) => char.charCodeAt(0));
return await crypto.subtle.verify("HMAC", key, expected, encoder.encode(body));
} catch {
return false;
}
}
Add the plugin to your config:
import { shop } from "./cms/plugins/shop";
export default defineCms({
// ...
plugins: [shop],
});
In the shop system, set the webhook URL to https://example.com/_tenon/shop/webhook, and copy its secret to SHOP_WEBHOOK_SECRET.
Why a job
- The
cmsof a public route has no user, so the access rules deny its writes. Thecmsof a task is the server API and skips them. - The route answers at once. A sender expects a quick answer and retries when it gets none.
- A failed write retries, and Manage → Jobs shows it.
Check every request
The route is public, so anyone can call it.
- Check the signature before you use the payload. Answer
401when it does not match. - Read the body as text first. The signature covers the exact bytes, so a body that is parsed and serialized again no longer matches.
- Each sender signs in its own way. The example checks a base64 HMAC-SHA256 of the body, which many services use. Follow the docs of your sender. If it follows Standard Webhooks,
verifyWebhook(c.req.raw, secret)fromtenoncmschecks it. - A sender can send the same event twice. Write the task so that running it twice does no harm, like setting a price.
- The task writes through the local API, so the field rules still apply. A
pricethat is not a number fails the job.
Related resources
- Plugins: what else a plugin can add.
- API keys: permissions for a sender that calls the API.
- Send webhooks: the other direction, from Tenon to another service.