Home > Software engineering >  Cannot set headers after they are sent to the client in stripe
Cannot set headers after they are sent to the client in stripe

Time:03-16

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;

CodePudding user response:

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

CodePudding user response:

In the catch block you are not returning.

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