What you see
Your Stripe webhook works when you test it with the Stripe CLI. Then you (or your AI assistant) add an automated test so CI can catch regressions, and it fails with one of these:
StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
StripeSignatureVerificationError: Timestamp outside the tolerance zone
StripeSignatureVerificationError: No stripe-signature header value was provided.
Or the test “passes” because someone mocked out constructEvent, which means the one check that stops forged “payment succeeded” events isn’t tested at all.
Why it happens
stripe.webhooks.constructEvent() recomputes the signature from three things: the exact bytes of the body, the timestamp in the Stripe-Signature header, and your whsec_ signing secret. A test request breaks it in a few predictable ways:
- The CLI isn’t a CI tool. Stripe’s webhook docs test handlers with
stripe listen --forward-to localhost:4242/webhook, which forwards events “from your account to your local listener” and prints the signing secret to use. That needs a logged-in CLI and a Stripe account, which you don’t want in every CI run. - The body you signed isn’t the body you sent. In stripe/stripe-node #1504, a developer followed the README’s test example and kept getting “No signatures found” until they changed
JSON.stringify(payload, null, 2)toJSON.stringify(payload). A Stripe maintainer explained that the payload passed togenerateTestHeaderStringmust be the same as the one passed toconstructEvent, and a test client that gets an object “will serialize your object under the hood and may not callJSON.stringifywith the same parameters.” - The signature is too old. Stripe’s libraries “have a default tolerance of 5 minutes between the timestamp and the current time” (Stripe docs). In stripe-node that’s
DEFAULT_TOLERANCE: 300seconds (source), so a header copied from a real delivery into a fixture file stops working five minutes later. - The secret differs. A test that signs with one secret while the handler reads another from the environment gets the same “No signatures found” message.
Fix it: sign your own test events
stripe-node ships a helper for exactly this. The README says: “You can use stripeClient.webhooks.generateTestHeaderString to mock webhook events that come from Stripe.” It computes a valid Stripe-Signature header for any payload and secret, locally, with no API call. (The Stack Overflow question on this has an older answer that builds the HMAC by hand; the helper replaces that.)
1. A typical handler (Next.js App Router)
Nothing changes in your production code. This is the usual shape:
// app/api/webhooks/stripe/route.ts
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: Request) {
const body = await req.text(); // the raw body, not req.json()
const signature = req.headers.get('stripe-signature');
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature!, process.env.STRIPE_WEBHOOK_SECRET!);
} catch (err) {
return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 });
}
if (event.type === 'checkout.session.completed') {
// mark the order as paid
}
return new Response(null, { status: 200 });
}
2. The test
This uses Node’s built-in test runner, but the same code works in Vitest or Jest. It calls the route function directly, so there’s no server to start:
// app/api/webhooks/stripe/route.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import Stripe from 'stripe';
// Test-only values. Never put your real keys or whsec_ in CI.
process.env.STRIPE_SECRET_KEY = 'sk_test_not_a_real_key';
process.env.STRIPE_WEBHOOK_SECRET = 'whsec_test_only_not_a_real_secret';
const { POST } = await import('./route');
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const secret = process.env.STRIPE_WEBHOOK_SECRET;
const event = {
id: 'evt_test_checkout',
object: 'event',
type: 'checkout.session.completed',
data: { object: { id: 'cs_test_123', object: 'checkout.session', payment_status: 'paid' } },
};
function signedRequest(evt: object, opts: { timestamp?: number } = {}) {
const payload = JSON.stringify(evt); // serialize ONCE
const header = stripe.webhooks.generateTestHeaderString({ payload, secret, ...opts });
return new Request('http://localhost/api/webhooks/stripe', {
method: 'POST',
body: payload, // send the SAME string you signed
headers: { 'stripe-signature': header, 'content-type': 'application/json' },
});
}
test('accepts a correctly signed event', async () => {
const res = await POST(signedRequest(event));
assert.equal(res.status, 200);
});
test('rejects a request with no signature', async () => {
const res = await POST(new Request('http://localhost/api/webhooks/stripe', { method: 'POST', body: JSON.stringify(event) }));
assert.equal(res.status, 400);
});
test('rejects an event signed more than 5 minutes ago', async () => {
const res = await POST(signedRequest(event, { timestamp: Math.floor(Date.now() / 1000) - 600 }));
assert.equal(res.status, 400);
});
We ran this pattern against stripe-node 23.2.0 on Node 20: all three tests pass, and the unsigned request returns Webhook Error: No stripe-signature header value was provided.
Details that matter:
timestampis in seconds. The helper defaults toMath.floor(Date.now() / 1000)(source). Pass an older value only when you want to test the tolerance check.- Make the fixture realistic enough for your handler.
constructEventonly verifies the signature and parses the JSON; it doesn’t call Stripe. If your handler then fetches the session from the API, mock that call separately. - Use one secret. The handler and the test both read
process.env.STRIPE_WEBHOOK_SECRET, so they can’t drift apart.
3. If you use supertest or another HTTP client
Send the string, not the object. With supertest that’s .set('stripe-signature', header).set('content-type', 'application/json').send(payload) where payload is the string you signed. If you pass the object, the client serializes it its own way, which is the mismatch from #1504. For Express, the webhook route also has to receive the raw body (express.raw({ type: 'application/json' })), as covered in the signature verification guide.
4. Supabase Edge Functions and other Web Crypto runtimes
Deno and edge runtimes verify with constructEventAsync and Stripe.createSubtleCryptoProvider(), as in Supabase’s Stripe webhook example. In the test, sign with the async helper and the same provider:
const cryptoProvider = Stripe.createSubtleCryptoProvider();
const header = await stripe.webhooks.generateTestHeaderStringAsync({ payload, secret, cryptoProvider });
If you call the sync version with that provider, stripe-node throws SubtleCryptoProvider cannot be used in a synchronous context. and tells you to use the Async variant.
Don’t “fix” the test by weakening the handler
- Don’t mock
constructEventaway. The point of the test is that a forged event gets a 400. - Don’t set the tolerance to 0. Stripe’s docs: “Don’t use a tolerance value of
0. Using a tolerance value of0disables the recency check entirely.” Sign with a fresh timestamp instead. - Don’t add a “skip verification in test mode” flag that could ever be true in production.
- Verifying later, in a queue? Pass the time the request arrived as
receivedAt, the sixth argument ofconstructEvent(payload, header, secret, tolerance?, cryptoProvider?, receivedAt?). medusajs/medusa #17261 shows what happens otherwise: a job that runs more than 300 seconds after Stripe signed the delivery fails with “Timestamp outside the tolerance zone”, after the endpoint already answered 200, so Stripe never retries.
Check it worked
- The signed test passes locally and in CI, with no Stripe CLI and no network.
- Temporarily change the handler to
req.json()and re-run: the signed test should now fail. Change it back. - The three failure tests return 400.
- Your CI config contains no real
sk_orwhsec_values.
Webhook handlers that only work on the founder’s laptop are a common reason paid orders never unlock. For a no-signup scan of your live site, run the free production-readiness checker. If you want someone to review your payment flow end to end (webhook verification, idempotency, test vs live keys, what happens when a delivery fails), get a written pre-launch audit.