Skip to content
jshacks.dev
APIs

Verify Stripe webhook signature

Verify a Stripe webhook signature with stripe.webhooks.constructEvent, passing the raw request body and the Stripe-Signature header.

1 min read
Summarize in AI

Stripe signs every webhook, and its library checks the signature and the timestamp for you. It needs the raw bytes of the body, so do not run express.json() on that route.

stripe-webhook.jsJavaScript
import Stripe from 'stripe';
import express from 'express';

const stripe = new Stripe('sk_test_placeholder');
const secret = 'whsec_test_secret';

const app = express();

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
  try {
    const event = stripe.webhooks.constructEvent(req.body, req.get('stripe-signature'), secret);
    console.log(event.type);
    res.sendStatus(200);
  } catch (err) {
    res.status(400).send('Invalid signature');
  }
});

const payload = JSON.stringify({ id: 'evt_1', object: 'event', type: 'ping' });
const header = stripe.webhooks.generateTestHeaderString({ payload, secret });

console.log(stripe.webhooks.constructEvent(payload, header, secret).id);

try {
  stripe.webhooks.constructEvent(payload + ' ', header, secret);
} catch (err) {
  console.log(err.type);
}
Text
evt_1
StripeSignatureVerificationError

The helper generateTestHeaderString builds a valid header for the demo; in the route, the header comes from the request. Changing one byte of the payload makes the check fail with a StripeSignatureVerificationError, so the route answers 400.

express.raw() keeps the body as a Buffer. If another middleware parses the JSON first, the bytes differ from what Stripe signed and every event fails. The default tolerance is five minutes. See Stripe's webhook signature guide.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.