Safe Webhook Handler Pattern

    1

    Standardized pattern for secure, idempotent, and non-blocking webhook integrations.

    $7

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    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.constructEvent requires the buffer.
    • Implement a persistent store (like Redis or your DB) for the seen_events check 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

    1. Review your current webhook handler code or architecture plan.
    2. Apply the five-step pattern covering verification, idempotency, data handling, and async execution.
    3. 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.

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.

    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. 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. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    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

    Permissions

    Network Access
    Listed18 days ago

    What's inside

    Frequently Asked Questions

    This skill provides a battle-tested architectural pattern and implementation framework that automates signature verification, prevents duplicate event processing (idempotency), and ensures non-blocking execution to keep your services responsive.

    Yes, the implementation pattern is language-agnostic and designed to work with any major backend framework, including Node.js, Python, Go, and Ruby, regardless of which AI agent platform you are using.

    The skill includes a comprehensive implementation guide, security checklists, and structural templates that can be integrated into your existing codebase in minutes.

    Unlike generic prompts, this skill accounts for edge cases like raw body parsing requirements and provider-specific retry logic that typically cause standard AI-generated code to fail signature checks.

    The pattern is designed to work with any service that sends signed HTTP POST requests, including Stripe, GitHub, Shopify, and Twilio, as long as you have access to the provider's signing secret.

    Updates to the core pattern and security checklists are included with your purchase, ensuring your handlers stay compliant with evolving web standards and newly discovered attack vectors.

    New in APIs & Backend