Ad

Error: Can't Set Headers After They Are Sent Because Of Res.?

- 1 answer

I'm trying to set up a method that is called with Shopify's webhook. I get the data and I'm able to store with a fresh server but I get "Error: Can't set headers after they are sent" returned in the console. I believe this is because I'm calling res twice. Any ideas on how to structure this better?

This is my method:

function createProductsWebHook(req,res,next) {
//if(req.headers){
//    res.status(200).send('Got it')
//     return next()
// }
 res.sendStatus(200) 
next()
const productResponse = req.body
console.log(productResponse)
const product = Product.build({
    body_html: req.body.body_html,
    title: req.body.title,
});
product.save()
    .then(saveProduct => res.json(saveProduct))
    .catch((e)=> {
        console.log(e)
    });
}
Ad

Answer

This occurs because the middleware, createProductsWebHook(), is called first when a request is received, which then sends a 200 status code response, res.sendStatus(200). Then in, in the same middleware function, product.save().then(...) is called. save()’s callback function attempts to send a response too – after one has already been sent by the very same middleware – using res.json(saveProduct).

Key Takeaway

Middleware should not send the response; this defeats the purpose of middleware. Middleware's job is to decorate (add or remove information, i.e, headers, renew some auth session asynchronously, perform side effects, and other tasks) from a request or response and pass it along, like a chain of responsibility, not transmit it – that's what your route handler is for (the one you registered your HTTP path and method with, e.g., app.post(my_path, some_middleware, route_handler).

Ad
source: stackoverflow.com
Ad