Handle Webhooks from an External Service
Build a robust webhook handler with signature verification, idempotency, and proper error handling.
5-10 min|Intermediate
BuildQuick WinDeveloper
Prompt Template
Build a webhook handler for my app. Check my existing integrations (payment provider, auth, CMS) and set up a webhook handler for the ones that need it. Events to handle: [list each event type and what your app should do] Example: - checkout.session.completed: create subscription record in database, send welcome email - customer.subscription.updated: update subscription status and period end date - customer.subscription.deleted: mark subscription as canceled, send churn email Requirements: 1. Signature verification: verify the webhook signature using the provider's secret before processing 2. Idempotency: handle duplicate webhook deliveries gracefully (don't double-process the same event) 3. Return 200 immediately, then process async (webhook providers retry on non-200 responses) 4. Log every webhook event received (event type, timestamp, success/failure) 5. Handle unknown event types gracefully (log and ignore, don't error) Error handling: - If processing fails after signature is verified: log the error, still return 200 (to prevent infinite retries), queue for manual review - If signature verification fails: return 401, log the attempt Do NOT return errors for events you don't handle. Just acknowledge them." **Output format:** Webhook route handler with signature verification and event processing.
The three critical requirements (signature verification, idempotency, immediate 200) prevent the three most common webhook bugs. Most tutorials only cover the first one.
Whenever you integrate with a service that sends webhooks (payments, auth, CMS, CI/CD).