Vibe Code Guardian
← All posts

Webhook Security in AI-Generated Code: Why Your Stripe and Supabase Webhooks Fail in Production

AI coding tools write webhook handlers that work in testing but fail under retries, out-of-order delivery, and timeouts. Here are the five failures that reach production and the minimal setup that survives.

Aaron Allen·

Webhook Security in AI-Generated Code: Why Your Stripe and Supabase Webhooks Fail in Production

Your AI-built app handles payments. Stripe sends a checkout.session.completed event. Your webhook handler updates the user's subscription status. You tested it in the Stripe dashboard. It worked. You deployed.

Two weeks later a customer emails: "I paid but my account still says free."

You check the logs. The webhook was delivered. Your handler returned 200. But the subscription row never got created.

This is not a Stripe bug. It is the default for AI-generated webhook handlers.

Why AI tools get webhooks wrong

When you ask an AI coding assistant to "add Stripe webhooks," it writes the happy path: verify the signature, parse the event, update the database. It does not write the code that handles what happens when the database is slow, the network hiccups, or Stripe retries the same event three times because your handler took twelve seconds to respond.

Webhooks are not API calls you control. They are asynchronous notifications from infrastructure you do not own. The AI optimises for the feature you described. It does not optimise for the operational reality of a public endpoint that must be idempotent, fast, and verifiable.

The same gaps appear on Supabase database webhooks, SendGrid event webhooks, Resend delivery webhooks, GitHub webhooks, and any service that pushes events to your app.

The five webhook failures that reach production

1. No idempotency: duplicate events create duplicate data

Stripe retries webhooks on any non-2xx response, and sometimes on slow 2xx responses. Supabase retries on failure. Most providers retry with exponential backoff.

Your AI-generated handler probably looks like this:

// What the AI writes
app.post('/webhook/stripe', async (req, res) => {
  const event = req.body
  if (event.type === 'checkout.session.completed') {
    await db.subscriptions.create({
      userId: event.data.object.metadata.userId,
      stripeSubscriptionId: event.data.object.subscription,
      status: 'active'
    })
  }
  res.json({ received: true })
})

If Stripe delivers the same event twice, which it will, you get two subscription rows for the same customer. The second insert either fails with a unique constraint violation (returning 500, triggering more retries) or succeeds and corrupts your data.

What you need: an idempotency key on every handler. Store the event ID (Stripe's event.id, Supabase's webhook ID) with a unique constraint. Check before you process.

// What should be there
app.post('/webhook/stripe', async (req, res) => {
  const event = req.body
  const eventId = req.headers['stripe-event-id'] || event.id

  const existing = await db.webhookEvents.findUnique({ where: { eventId } })
  if (existing) {
    return res.json({ received: true, duplicate: true })
  }

  await db.webhookEvents.create({ data: { eventId, provider: 'stripe' } })

  if (event.type === 'checkout.session.completed') {
    await db.subscriptions.upsert({
      where: { stripeSubscriptionId: event.data.object.subscription },
      create: { /* ... */ },
      update: { status: 'active' }
    })
  }

  res.json({ received: true })
})

The upsert on the subscription row handles the case where the webhook arrives out of order. The webhookEvents table with a unique constraint on eventId handles the duplicate delivery.

2. Signature verification that passes but does not verify

AI tools know the pattern: "verify the webhook signature." They write the code. But they often get the details wrong.

Common failures:

  • Using the wrong secret (the endpoint secret instead of the signing secret, or a test secret in production)

  • Verifying the signature but not checking the timestamp, so replay attacks from six months ago still pass

  • Catching the verification error and returning 200 anyway because "we don't want to break the flow"

// What the AI writes: looks correct, has gaps
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET

app.post('/webhook/stripe', express.raw({ type: 'application/json' }), (req, res) => {
  const sig = req.headers['stripe-signature']
  let event

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret)
  } catch (err) {
    console.log('Webhook signature verification failed:', err.message)
    return res.status(400).send(`Webhook Error: ${err.message}`)
  }

  // ... handle event
})

This looks fine. But if STRIPE_WEBHOOK_SECRET is not set in production (common when the AI writes the code but you forget to add the env var), constructEvent throws, the catch block logs it, and returns 400. Stripe retries. You never know because the logs are noise.

What you need: fail fast at startup if the secret is missing. Log the verification failure at error level, not log. Alert on repeated 400s from your webhook endpoint.

3. Handlers that take too long: timeouts trigger retries

Stripe expects a 2xx response within 10 seconds. Supabase gives you 30 seconds. If your handler does synchronous database work, sends emails, calls another API, or waits for a lock, you will exceed the limit.

The AI writes sequential code:

// What the AI writes: synchronous, slow
async function handleSubscriptionCreated(session) {
  const user = await db.users.findUnique({ where: { id: session.metadata.userId } })
  await sendWelcomeEmail(user.email)
  await createDefaultProject(user.id)
  await notifySlack(`New subscriber: ${user.email}`)
  await db.subscriptions.create({ /* ... */ })
}

Four awaits in sequence. If sendWelcomeEmail takes 3 seconds and notifySlack takes 2, you are at 5 seconds before the database write. Under load, this exceeds 10 seconds. Stripe retries. Your handler runs again. Now you have duplicate emails, duplicate Slack notifications, and a race condition on the subscription row.

What you need: acknowledge immediately, process asynchronously.

// What should be there
app.post('/webhook/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  const event = verifyAndParse(req) // throws on failure, returns event
  await db.webhookEvents.create({ data: { eventId: event.id, provider: 'stripe', payload: event } })
  res.json({ received: true }) // respond fast

  // Process in background: use a queue, not a fire-and-forget promise
  queue.add('process-stripe-event', { eventId: event.id })
})

Then a separate worker picks up the event, processes it with retries, dead-letter handling, and visibility into what succeeded or failed.

4. No handling for out-of-order delivery

Events do not arrive in order. A customer.subscription.updated can arrive before checkout.session.completed. A invoice.payment_failed can arrive before the subscription exists in your database.

AI-generated handlers assume order. They write findUnique then update, and crash when the record does not exist.

What you need: upsert patterns that work regardless of arrival order. Design your database schema so the webhook handler can create or update the target record in one operation.

// Works whether the subscription row exists or not
await db.subscriptions.upsert({
  where: { stripeSubscriptionId: subscription.id },
  create: {
    stripeSubscriptionId: subscription.id,
    userId: subscription.metadata.userId,
    status: subscription.status,
    currentPeriodEnd: new Date(subscription.current_period_end * 1000)
  },
  update: {
    status: subscription.status,
    currentPeriodEnd: new Date(subscription.current_period_end * 1000)
  }
})

5. No visibility: you do not know when webhooks fail

The AI writes a handler. It returns 200. You assume it works. You have no dashboard, no alerts, no way to answer "did the webhook for customer X actually process?"

What you need: a webhook event log table with status (received, processing, completed, failed, duplicate). A simple admin view showing recent events, their status, and the error message for failures. An alert when failed count exceeds a threshold in 5 minutes.

A practical webhook audit you can run today

You do not need to rewrite everything. Start with these checks on your live endpoints.

Check 1: Can you replay a webhook safely?

Go to your Stripe dashboard → Developers → Webhooks. Pick a recent checkout.session.completed event. Click "Resend." Does your app handle it cleanly, or does it create a duplicate subscription, throw a 500, or silently do nothing?

Check 2: Are you verifying signatures with the right secret?

In your hosting dashboard (Vercel, Netlify, Railway, Fly.io), check the environment variables. Is STRIPE_WEBHOOK_SECRET set to the endpoint-specific secret from Stripe (starts with whsec_), not the account-wide signing secret? Is it different between staging and production?

Check 3: What happens when your database is slow?

Simulate latency: add await new Promise(r => setTimeout(r, 12000)) at the top of your handler. Trigger a webhook. Does Stripe retry? Does your handler run twice? Do you get duplicate data?

Check 4: Can you see failed webhooks in the last 24 hours?

Query your database: SELECT * FROM webhook_events WHERE status = 'failed' AND created_at > NOW() - INTERVAL '24 hours'. If you do not have a webhook_events table, you have no visibility. That is the finding.

Check 5: Are you using upsert or create on the target records?

Search your webhook handlers for .create( on the business entities (subscriptions, orders, users). Every one is a potential duplicate on retry. Change to upsert with a unique constraint on the provider's ID (Stripe subscription ID, Supabase record ID, etc.).

The minimal webhook setup that survives production

If you are building a new endpoint today, this is the baseline:

  1. Raw body parser: Stripe and others need the raw bytes for signature verification. Do not use express.json() on the webhook route.

  2. Signature verification at the edge: Verify before you touch your database. Fail fast with 400 on invalid signatures.

  3. Idempotency key on receipt: Store the provider's event ID with a unique constraint. Return 200 immediately for duplicates.

  4. Acknowledge fast, process async: Respond 200 within 1 second. Push to a queue (BullMQ, pg-boss, Cloudflare Queues, or a simple webhook_jobs table with a cron worker).

  5. Upsert on business records: Never .create() the thing the webhook is about. Always .upsert() on the provider's unique ID.

  6. Structured logging: Every webhook receipt, every processing start, every completion, every failure. Include eventId, eventType, provider, durationMs, error.

  7. Alert on failure rate: If more than 5% of webhooks fail in a 5-minute window, page someone.

How Vibe Code Guardian checks this

The free surface check at vibecodeguardian.co.uk/free-check scans your deployed app for publicly visible webhook endpoints and checks whether they return 200 without obvious signature verification. It does not test idempotency, replay safety, or queue architecture: those require code access.

The launch-readiness audit covers 137 points across 14 areas, including a full webhook review: we verify your idempotency keys, signature verification, queue setup, upsert patterns, and observability. A developer confirms every finding.

What to do next

Pick one webhook endpoint in your app. Run the five checks above. Fix what fails. Then move to the next endpoint.

The goal is not perfect webhook handling on day one. The goal is knowing which endpoints will corrupt data when (not if) the provider retries, and fixing them before a real customer pays and gets nothing.

Want a developer to look at your app?

Built your app with AI tools? Run the free surface check yourself in a few minutes. Nothing to buy, and we never look at your app unless you run it.