- Home
- Skills
- APIs & Backend
- Safe Webhook Handler Pattern
Safe Webhook Handler Pattern
Standardized pattern for secure, idempotent, and non-blocking webhook integrations.
$7
Works with the AI Agents you already use
Safe Webhook Handler Pattern
Example session with this skill installed
I need to build a Node.js endpoint to receive Stripe checkout.session.completed events. How should I structure the handler to be secure and handle retries?
- Read your context and instructions
- Compiled the safe webhook handler
I will outline the safe webhook handler pattern for your Node.js Stripe endpoint, focusing on signature verification and idempotency.
Secure Webhook Handler Structure
// Example: Express.js with raw body support
app.post('/webhooks/stripe', express.raw({type: 'application/json'}), async (req, res) => {
const sig = req.headers['stripe-signature'];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event;
// 1. Verify signature using RAW body
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
console.error(`Signature verification failed: ${err.message}`);
return res.status(400).send('Webhook Error');
}
// 2. Idempotency check (Deduplication)
const eventId = event.id;
if (await cache.has(`processed_event:${eventId}`)) {
return res.status(200).json({ received: true, duplicate: true });
}
// 3. Acknowledge fast
res.status(200).json({ received: true });
// 4. Process safely and asynchronously
try {
await processOrder(event.data.object);
await cache.set(`processed_event:${eventId}`, true, 'EX', 86400);
} catch (processErr) {
// 5. Fail loud
await deadLetterQueue.push({ event, error: processErr.message });
}
});
Next steps
- Ensure your Express middleware does not parse the body globally, as
stripe.webhooks.constructEventrequires the buffer. - Implement a persistent store (like Redis or your DB) for the
seen_eventscheck to handle horizontal scaling. - Configure an alert on your dead-letter queue to monitor post-acknowledgment failures.
Connects securely to your tools. The creator never sees your data.
About this skill
Webhook endpoints are public by design, making them high-value targets for forgery and replay attacks. Most developers stop at "it works in the dashboard test," leaving systems vulnerable to double-billing, prompt injection, and silent failures during retry storms.
This skill provides a rigorous implementation pattern for building production-ready webhook handlers. It ensures every incoming event is authenticated, deduplicated, and safely processed without blocking the provider's request.
What it does
- Signature verification ensures every payload is authenticated against a shared secret before processing.
- Event deduplication prevents race conditions and duplicate actions by tracking provider event IDs.
- Asynchronous processing improves reliability by acknowledging receipts immediately and handling logic out-of-band.
- Input sanitization treats all payload fields as untrusted data to prevent injection into downstream queries or LLM prompts.
- Failure observability implements patterns for dead-letter queues to ensure failed events are never lost.
How it works
- Review your current webhook handler code or architecture plan.
- Apply the five-step pattern covering verification, idempotency, data handling, and async execution.
- Verify the implementation against the migration checklist.
Frameworks & tools
Works with any backend stack including Node.js (Express/Next.js), Python (FastAPI/Flask), Go, and Ruby on Rails. Compatible with providers like Stripe, GitHub, Twilio, and Shopify.
Why this beats prompting it yourself
Standard prompts often miss the nuance of raw body verification, leading to broken signatures after middleware parsing. This skill enforces a "defense-in-depth" approach that handles the specific retry behaviors of major providers that generic AI often overlooks.
Use cases
- Payment processing to prevent double-charging users during Stripe retry storms.
- CI/CD triggers to securely handle incoming GitHub repository events.
- Agentic workflows where webhooks trigger autonomous actions based on external platform state changes.
- Legacy refactoring to audit and secure existing, unprotected POST endpoints.
Known limitations
Does not provide specific hash algorithms for every individual provider. Assumes the user has access to the provider's developer documentation for header names and secret management.
Does not provide specific code for every provider's unique HMAC implementation. Focuses on the architectural pattern rather than specific WAF or rate-limiting configurations.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 18 days ago