Header error while registering a new webhook in my shopify app

Highlighted
New Member
5 0 0

I am trying to register a new webhook as soon as the user opens my Shopify app but while redirecting I am getting the following error:

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Here is my code to do so:

let accessToken = ''app.get('/shopify/register_webhook', (req, res) => {
  const { shop, hmac, code, state } = req.query;
  const stateCookie = cookie.parse(req.headers.cookie).state;

  // Verifying Cookie
  if (state !== stateCookie) {
    return res.status(403).send('Request origin cannot be verified');
  }

  // Verifying Hmac
  if (shop && hmac && code) {
    const map = Object.assign({}, req.query);
    delete map['hmac'];
    const message = querystring.stringify(map);
    const generatedHash = crypto
      .createHmac('sha256', apiSecret)
      .update(message)
      .digest('hex');

    if(generatedHash !== hmac){
      return res.status(400).send('HMAC verification failed');
    }

    // Appending Access Token to the shop Url
    const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
    const accessTokenPayload = {        client_id: apiKey,        client_secret: apiSecret,        code
    };

    // Making an API Request And getting an API response    request.post(accessTokenRequestUrl, {json: accessTokenPayload })
    // Promise for Access Token Response
      .then((accessTokenResponse) => {        accessToken = accessTokenResponse.access_token;        res.redirect('/webhook');
    }).catch((error) => {      res.send(error.statusCode).send(error);
    })
  } else {    res.status(400).send('Required parameters missing');
  }
});app.get('/webhook', (req, res) => {
  const apiRequestUrl = 'https://'+shop+'/admin/webhooks.json';
        const apiRequestHeader = {
            'X-Shopify-Access-Token': accessToken,
            'Content-type': 'application/json'
        };
        let address = forwardingAddress+'/shopify/webhook';
        let payload = {
          "webhook": {
            "topic": "app/uninstalled",
            "address": address,
            "format": "json"
          }
        };  
        request.post({          url: apiRequestUrl,          body: payload,          headers: apiRequestHeader,          json: true
         })
        .then((apiResponse) => {          res.send('ok');
          // End API Response          res.end(apiResponse)
        }).catch((error) => {          res.send(error.statusCode).send(error);
        });
});

So I am redirecting to a new endpoint but still getting the same error. I have to provide the access token also in the header.

Can someone help me

0 Likes