To receive a webhook in Astro, create an on-demand endpoint such as src/pages/api/webhooks/payments.ts that exports a POST handler, reads the raw request body with await request.text(), verifies the sender’s signature header against a shared secret, and then returns a 2xx response quickly. Signature verification is the step people skip and the one that matters: without it, anyone who finds the URL can send fake events.
Key Takeaways
- Webhook endpoints need an adapter and
export const prerender = false.- Read the body as text first; signatures are computed over the exact bytes sent.
- Verify an HMAC signature with the Web Crypto API, which works in Node.js and edge runtimes.
- Form-encoded webhooks are blocked by
security.checkOriginunless you disable it.
A verified webhook endpoint
Most providers sign the body with HMAC-SHA256 using a secret you share, and send the result in a header. Header names and encodings differ, so check your provider’s docs; this example uses a hex signature in x-signature:
// src/pages/api/webhooks/payments.ts
import type { APIRoute } from 'astro';
import { WEBHOOK_SECRET } from 'astro:env/server';
export const prerender = false;
const encoder = new TextEncoder();
async function hmacHex(secret: string, body: string) {
const key = await crypto.subtle.importKey(
'raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
);
const sig = await crypto.subtle.sign('HMAC', key, encoder.encode(body));
return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
function safeEqual(a: string, b: string) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
export const POST: APIRoute = async ({ request }) => {
const body = await request.text();
const received = request.headers.get('x-signature') ?? '';
const expected = await hmacHex(WEBHOOK_SECRET, body);
if (!safeEqual(received, expected)) {
return new Response('Invalid signature', { status: 401 });
}
const event = JSON.parse(body);
switch (event.type) {
case 'payment.succeeded':
// ...mark the order paid
break;
default:
// ignore events you do not handle
}
return new Response(null, { status: 204 });
};
Declare WEBHOOK_SECRET in astro.config.mjs with envField.string({ context: 'server', access: 'secret' }) so it is never bundled for the browser. Our environment variables guide shows the full schema.
Why read the body as text
If you call request.json() first and then re-serialise the object to check the signature, spacing and key order can change and the signature will not match. Read request.text() once, verify that string, then JSON.parse it. A request body can only be read once, so do not call both text() and json().
Prevent replays
Many providers also send a timestamp, often included in the signed payload. Reject events older than a few minutes:
// src/pages/api/webhooks/payments.ts (after verifying the signature)
const sentAt = Number(request.headers.get('x-timestamp')) * 1000;
if (!Number.isFinite(sentAt) || Math.abs(Date.now() - sentAt) > 5 * 60_000) {
return new Response('Stale event', { status: 400 });
}
Providers also retry when they do not get a 2xx in time, so the same event can arrive twice. Store processed event IDs and skip repeats.
Respond fast
Providers typically time out after a few seconds and retry. Verify, record the event, and return 204. Do slow work, such as sending emails or calling other APIs, afterwards: in a queue, a background job, or your platform’s “wait until” mechanism if it has one. Returning 5xx deliberately is fine when you want a retry.
Form-encoded webhooks and checkOrigin
Astro’s security.checkOrigin is on by default. On on-demand routes it rejects POST requests whose Origin does not match your site when the body is application/x-www-form-urlencoded, multipart/form-data or text/plain, or when no content type is sent. Server-to-server webhooks send no Origin, so:
- JSON webhooks (
Content-Type: application/json) pass and reach your handler. - Form-encoded webhooks, which some SMS, voice and chat providers send, get a
403“Cross-site POST form submissions are forbidden” before your code runs.
For those providers, set security: { checkOrigin: false } in astro.config.mjs and protect your own forms with a CSRF token instead. Signature verification still protects the webhook route itself.
Test locally
Run npm run dev and send a signed request with curl, computing the signature with openssl:
# Terminal
BODY='{"type":"payment.succeeded","id":"evt_1"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -i -X POST http://localhost:4321/api/webhooks/payments \
-H "Content-Type: application/json" -H "x-signature: $SIG" -d "$BODY"
To receive real events on your laptop, use your provider’s CLI forwarding tool or a tunnel. Our API endpoints guide covers endpoint basics, and if the webhook should trigger a rebuild, see rebuilding Astro when CMS content changes. The Astro themes in our catalog are static, so add an adapter before adding webhook routes.
FAQ
How do I receive a webhook in Astro?
Create an endpoint with export const prerender = false and a POST handler, read the body with request.text(), verify the provider’s signature, process the event and return a 2xx status. An adapter is required.
Why does my Astro webhook return 403?
The provider is probably sending a form-encoded body, which security.checkOrigin blocks for cross-site requests. Set checkOrigin: false in the security config and keep verifying signatures.
Why does my webhook signature never match?
You are probably verifying a re-serialised object instead of the raw body, using the wrong secret, or comparing different encodings (hex versus base64). Verify the exact string from request.text().
Can webhooks work on a static Astro site?
No. A static site has no code running at request time. Add an adapter for that one route, or point the webhook at a separate serverless function.