Fixing Stripe Webhook Timeouts on Vercel and Next.js
Why Stripe webhooks time out on Vercel serverless functions, how Stripe's 3-day exponential backoff works, and how to acknowledge fast, verify signatures, and replay payloads locally.
If your Next.js application runs on Vercel, one of the most common production bugs is a webhook handler that works reliably in local development and then silently drops checkout.session.completed or invoice.paid events under real traffic.
Usually, Stripe is not failing to send the webhook. Your serverless route is taking too long to respond—or failing signature verification—and triggering timeout retries.
How Stripe Webhook Retries Actually Work
In live mode, Stripe expects your endpoint to return a 2xx HTTP status code promptly. If your server returns a non-2xx status (such as 500 or 504 Gateway Timeout) or fails to respond before Stripe’s connection timeout, Stripe retries delivery for up to 3 days using exponential backoff. (In test mode, Stripe uses a shorter retry schedule with fewer attempts.)
While a 3-day retry window sounds forgiving, timeouts in serverless environments create three serious problems:
- Duplicate side effects: If your handler charges a credit, sends a welcome email, and writes to Postgres before timing out on a downstream API call, Stripe assumes delivery failed and sends the exact same event again.
- Delayed fulfillment: Exponential backoff quickly spaces retries from minutes to hours. Customers who just paid sit waiting for access until the next retry succeeds.
- Disabled endpoints: If an endpoint fails consistently for days, Stripe eventually marks it as disabled and stops sending events altogether.
Why Vercel Serverless Functions Time Out on Webhooks
Serverless platforms introduce three failure modes that rarely show up against localhost:
- Cold starts + heavyweight SDK initialization: Importing an ORM, Stripe SDK, email client, and PDF generator inside a single App Router route handler can burn several seconds before your business logic even starts.
- Synchronous downstream work: Calling a slow database, third-party CRM, or transactional email provider inline before returning
NextResponse.json({ received: true })keeps the HTTP connection open and invites a504timeout. - Body parsing mistakes: Next.js middleware or helper wrappers that call
req.json()before Stripe verifies theStripe-Signatureheader alter whitespace/formatting and causestripe.webhooks.constructEventto throw400errors on every retry.
The Fix: Verify Raw Bytes, Deduplicate, and Acknowledge Fast
A resilient Next.js App Router handler (app/api/webhooks/stripe/route.ts) follows three rules:
- Read the exact raw request body with
await req.text(). - Verify
Stripe-Signatureimmediately—do no database or network work beforehand. - Persist or enqueue the event idempotently using
event.id, then return200 OKas quickly as possible.
import Stripe from "stripe";
import { after, NextRequest, NextResponse } from "next/server";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: NextRequest) {
const signature = req.headers.get("stripe-signature");
if (!signature) {
return NextResponse.json({ error: "Missing stripe-signature" }, { status: 400 });
}
// Always read the unparsed raw body before signature verification
const rawBody = await req.text();
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
rawBody,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
const message = err instanceof Error ? err.message : "Invalid signature";
return NextResponse.json({ error: message }, { status: 400 });
}
// Step 1: Record event.id in your database with a UNIQUE constraint.
// If already processed, return 200 immediately so Stripe stops retrying.
const alreadyProcessed = await markEventStarted(event.id, event.type);
if (alreadyProcessed) {
return NextResponse.json({ received: true, duplicate: true });
}
// Step 2: Defer slow fulfillment work (emails, CRM sync, invoices)
// after() runs post-response on Vercel; for critical jobs, enqueue to a durable queue.
after(async () => {
await processStripeEvent(event);
});
// Step 3: Acknowledge within milliseconds
return NextResponse.json({ received: true }, { status: 200 });
}
async function markEventStarted(eventId: string, eventType: string): Promise<boolean> {
// Replace with an atomic INSERT ... ON CONFLICT DO NOTHING on event_id
console.log("Recording Stripe event", eventId, eventType);
return false;
}
async function processStripeEvent(event: Stripe.Event): Promise<void> {
if (event.type === "checkout.session.completed") {
// Fulfill order, provision seat, send receipt
}
}
Important Caveat on after() vs. Durable Queues
after() in Next.js lets you return 200 OK immediately while finishing lightweight work in the background, but it is still bound by your Vercel function’s maxDuration and does not provide multi-hour retry queues if your database goes down for 10 minutes. For mission-critical billing events, persist the verified payload or enqueue it to a durable worker queue before returning 200. You should also design handlers to be safe against out-of-order delivery—for example, checking the Stripe object’s status or timestamp before overwriting subscription state if customer.subscription.updated arrives ahead of invoice.paid.
Inspecting and Replaying Stripe Webhooks Locally with EdgeHook
When debugging timeout edge cases or malformed checkout metadata, re-creating a full Stripe Checkout session for every code tweak wastes time. You can inspect and replay real payloads locally today using EdgeHook’s Day-1 live tools:
- Create a 24-hour sandbox: Open EdgeHook to automatically provision a temporary
/in/:idcapture URL on Cloudflare Workers (no signup required; events up to 256 KB are retained for 24 hours). - Send a test webhook from Stripe: Add your
/in/:idURL as a Stripe test-mode webhook destination and inspect theStripe-Signatureheader, HTTP metadata, and formatted JSON in real time. - Pull and replay locally with
edgehook-cli:
# Pull captured events from your 24h EdgeHook sandbox
npx edgehook-cli pull <sandbox-url-or-id> --save ./.edgehook/events
# Replay saved events against your local Next.js route handler
npx edgehook-cli replay ./.edgehook/events --to http://localhost:3000/api/webhooks/stripe
You can also run edgehook listen --port 4000 --forward http://localhost:3000/api/webhooks/stripe --save ./.edgehook/events to capture and save every local event as JSON so you can replay the same failure case repeatedly.
(Tip: stripe.webhooks.constructEvent rejects timestamps older than 300 seconds by default. When replaying older captured fixtures in local development, pass an explicit tolerance parameter such as Number.MAX_SAFE_INTEGER only in non-production test environments.)
What Is Live Today vs. On the Roadmap
We want to be completely transparent about what EdgeHook provides today versus what is still in development:
- Live today (Day 1): Unauthenticated 24-hour webhook sandbox (
/in/:idcapture and/api/sandbox/:id/eventsinspection), the zero-dependency open-sourceedgehook-cli(listen,replay,pull,send), the waitlist, and Founding Member pre-order access via Polar when enabled. - On the roadmap (not yet live): Hosted multi-tenant production proxy endpoints, fast edge
200 OKACKs with automatic exponential retries when Vercel times out, managed edge signature verification, hosted 1-click dashboard replay, Slack/Discord failure alerts, and paid retention tiers (planned: Indie at $29/mo for 14-day retention and Pro at $49/mo for 30-day retention).
Next Steps
- Capture and inspect a Stripe payload right now: Open the live 24h webhook sandbox at EdgeHook.
- Want edge-buffered retries in front of Vercel? Join the early access waitlist at /#waitlist (or lock in Founding Member access when Polar checkout is active).
- Explore the CLI source: View
edgehook-cliat /.
Debug your webhooks in seconds
Inspect real Stripe, Shopify, or Clerk payloads in our free 24-hour Cloudflare Workers sandbox (live today), or join the waitlist for managed retries and replay.