DEV Community

delay.run
delay.run

Posted on Edited on

How to fix 'No signatures found matching the expected signature for payload' (Stripe webhooks in Express, Next.js and Flask)

Reliable HTTP cron and delayed-job scheduling with automatic retries and full run logs — delay.run

You've set up a Stripe webhook endpoint, sent a test event, and your logs say:

No signatures found matching the expected signature for payload.
Are you passing the raw request body you received from Stripe?
Enter fullscreen mode Exit fullscreen mode

The second sentence is the hint, and it's right most of the time. Stripe signs the exact bytes of the request body. If your framework parses the JSON and you verify the re-serialised version, or you use a secret from a different endpoint, the signature can't match.

Here are the causes in order of how often they happen, and how to check for each.

How the check works, in one paragraph

Stripe sends a Stripe-Signature header like t=1731571200,v1=5257a8.... To verify, the library computes an HMAC-SHA256 of "{t}.{raw body}" using your endpoint's signing secret (whsec_...) and compares it with v1. If even one byte of the body differs (a space, key order, a Unicode escape, a newline), the HMAC is completely different. There's no "close enough".

Cause 1: the body was parsed before you verified it

By far the most common. A global JSON body parser runs on every route, including the webhook route, and by the time your handler runs, the raw bytes are gone.

Express

Mount the webhook route with express.raw() before any global express.json():

const express = require("express");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const app = express();

app.post("/webhooks/stripe", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,                              // a Buffer, untouched
      req.headers["stripe-signature"],
      process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch (err) {
    console.error("Webhook signature check failed:", err.message);
    return res.sendStatus(400);
  }
  // enqueue event.id / event.type for processing, then:
  res.sendStatus(200);
});

app.use(express.json()); // everything else gets parsed JSON
Enter fullscreen mode Exit fullscreen mode

Quick check: log Buffer.isBuffer(req.body) in the handler. If it prints false, something parsed the body first.

Next.js App Router

Read the body as text, not JSON:

// app/api/webhooks/stripe/route.js
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

export async function POST(req) {
  const body = await req.text();
  const sig = req.headers.get("stripe-signature");
  try {
    const event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET);
    // handle event
    return new Response(null, { status: 200 });
  } catch (err) {
    return new Response(`Webhook Error: ${err.message}`, { status: 400 });
  }
}
Enter fullscreen mode Exit fullscreen mode

Calling await req.json() anywhere before this, including in middleware that reads the body, breaks it.

Next.js Pages Router

Pages API routes parse the body by default. Turn that off for this route and read the raw stream:

// pages/api/webhooks/stripe.js
export const config = { api: { bodyParser: false } };

async function rawBody(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  return Buffer.concat(chunks);
}

export default async function handler(req, res) {
  const buf = await rawBody(req);
  const event = stripe.webhooks.constructEvent(buf, req.headers["stripe-signature"], process.env.STRIPE_WEBHOOK_SECRET);
  // ...
  res.status(200).end();
}
Enter fullscreen mode Exit fullscreen mode

Flask

Use request.get_data(), never request.json or request.get_json() before verifying:

import os, stripe
from flask import Flask, request

app = Flask(__name__)
endpoint_secret = os.environ["STRIPE_WEBHOOK_SECRET"]

@app.post("/webhooks/stripe")
def stripe_webhook():
    payload = request.get_data()  # raw bytes
    sig = request.headers.get("Stripe-Signature", "")
    try:
        event = stripe.Webhook.construct_event(payload, sig, endpoint_secret)
    except (ValueError, stripe.SignatureVerificationError) as e:
        app.logger.warning("Stripe webhook rejected: %s", e)
        return "", 400
    # enqueue event["id"], then:
    return "", 200
Enter fullscreen mode Exit fullscreen mode

In older versions of the Python library, the exception lives at stripe.error.SignatureVerificationError.

Cause 2: the wrong signing secret

Every webhook endpoint has its own secret, and so does the Stripe CLI. Common mix-ups:

  • Using the secret printed by stripe listen in production, or the dashboard endpoint's secret while testing with stripe listen.
  • Test mode and live mode endpoints have different secrets.
  • Two endpoints (say, staging and production) pointing at the same server, with only one secret configured.
  • Using your API secret key (sk_...) instead of the webhook signing secret (whsec_...).

Check: in the dashboard, open the endpoint the event was sent to (the event's delivery log shows which), reveal its signing secret and compare the last four characters with what your server loaded. Print only the last four in your logs, never the whole secret.

Once signatures verify, you still have to retry the work if your handler fails. delay.run takes the HTTP callback, retries it, and keeps the run log.

Cause 3: something between Stripe and your code changed the body

Proxies, API gateways, serverless adapters and some middleware re-encode bodies: they parse and re-stringify JSON, change the character encoding, or decompress and re-compress. Anything that touches the bytes breaks the signature.

Check: log the length of the body you received and compare it with the length shown in the event's delivery details in the dashboard. Different lengths mean something altered it. In AWS API Gateway and some serverless frameworks, look for a "binary" or "raw body" option, or for base64-encoded bodies that need decoding first.

Cause 4: the header isn't reaching you

If Stripe-Signature is missing or empty, verification fails with a similar error. Some proxies strip unknown headers. Log whether the header is present (not its value).

Cause 5: timestamps out of tolerance

This one has a different message ("Timestamp outside the tolerance zone"), but it gets confused with the others. Stripe's libraries reject signatures more than five minutes old by default, to prevent replays. If your server clock is wrong, or you're replaying an old event body by hand, you'll see it. Fix the clock (NTP); don't raise the tolerance.

After it works

Verify, store the event ID, return 200 quickly, and process in a background job. Signature checks prove who sent the event; they don't stop duplicates or out-of-order delivery, so the processing side still needs to be idempotent. Retrying the processing on your own schedule, rather than relying on Stripe's retries, is the kind of thing delay.run handles, but a database-backed queue works too.

Related reading

Which of these five got you? I'd bet on the global body parser for most people, but the CLI-versus-dashboard secret mix-up is a close second.

Top comments (0)