'Cannot set headers after they are sent to the client in stripe

I'm setting up a stripe webhook to check if the payment intent was successful or not. But while doing so, I'm getting this error Cannot set headers after they are sent to the client in stripe, what am I doing wrong in the route?

import express from 'express';
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: "2020-08-27" });

const router = express.Router();

router.post(
    "/webhook",
    express.raw({ type: "*/*" }),
    async (request, response) => {
        const sig = request.headers["stripe-signature"];

        let event;

        try {
            event = stripe.webhooks.constructEvent(
                request.body,
                sig,
                process.env.STRIPE_WEBHOOK_SECRET_KEY
            );
              console.log("type", event);
        } catch (err) {
            //   console.log("type2", err);
            response.status(400).send(`Webhook Error: ${err.message}`);
        }

        response.json({ received: true });
    }
);

export default router;


Solution 1:[1]

There's a section here https://stripe.com/docs/identity/handle-verification-outcomes that skips the body parsing if the url points to the webhook service

app.use((req, res, next) => {
  if (req.originalUrl === '/webhook') {
    next();
  } else {
    bodyParser.json()(req, res, next);
  }
});

That could be the issue: webhook expects you not to execute express.raw() if you're going to give him the request.body to analyse

Solution 2:[2]

You are trying to send a json response with response.json() after the error handling sends the 400 response with response.status(400).send() -- you can't do that.

You need to either move your response.json() to the end of the try block or have the catch block return (as @abhishek noted) to stop the execution.

Solution 3:[3]

In the catch block you are not returning.

catch (err) {
            //   console.log("type2", err);
            return response.status(400).send(`Webhook Error: ${err.message}`);
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nolan H
Solution 3 Abhishek Solanki