javascript
42 lines · 7 steps
Verifying Stripe webhooks in Express
An Express route that authenticates incoming Stripe events with a signature check before acting on them.
Explained by
highlit
1const express = require('express');
2const Stripe = require('stripe');
3
4const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
5const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
6
7const router = express.Router();
8
9router.post(
10 '/webhooks/stripe',
11 express.raw({ type: 'application/json' }),
12 async (req, res) => {
13 const signature = req.headers['stripe-signature'];
14
15 let event;
16 try {
17 event = stripe.webhooks.constructEvent(req.body, signature, endpointSecret);
18 } catch (err) {
19 console.error(`Webhook signature verification failed: ${err.message}`);
20 return res.status(400).send(`Webhook Error: ${err.message}`);
21 }
22
23 switch (event.type) {
24 case 'checkout.session.completed': {
25 const session = event.data.object;
26 await fulfillOrder(session);
27 break;
28 }
29 case 'invoice.payment_failed': {
30 const invoice = event.data.object;
31 await notifyPaymentFailure(invoice.customer);
32 break;
33 }
34 default:
35 console.log(`Unhandled event type: ${event.type}`);
36 }
37
38 res.json({ received: true });
39 }
40);
41
42module.exports = router;
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Webhook endpoints must verify a cryptographic signature so attackers can't forge events.
- 2Signature verification needs the unparsed raw body, so the usual JSON parser must be bypassed for this route.
- 3Acknowledge the webhook with a 2xx quickly and branch on event type to run the right side effect.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/verifying-stripe-webhooks-in-express-explained-javascript-bf2b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.