How to validate an incoming webhook GET request from the Twilio API using Node.js

51 views Asked by At

I have figured out how to validate incoming POST webhook requests from the Twilio API in Node. Now I am trying to do the same with a GET request. It keeps failing the validation. I have found very few good examples online of how to do a GET request.

Here is the relevant section of my NodeJS Express route:

router.get('/postatus', async (req, res) => {
    console.log('route /postatus');
    // we first need to make sure that the request actually came from Twilio,
    // so this code is to validate that incoming request
    const authToken = process.env.MY_TWILIO_AUTH_TOKEN_VAR;
    let url = 'https://myurl.com';
    
    let params = req.query;
    console.log({params});
    url += "?" + Object.keys(params).map(key => key + '=' + params[key]).join('&');
    params = {};
    
    const twilioSignature = req.headers['x-twilio-signature'];
    
    const validRequest = client.validateRequest(authToken, twilioSignature, url, params);
1

There are 1 answers

0
IObert On

It should work the same way as for POST. Maybe your not parsing the parameters the right way. I'd recommend using the twilio.webhook() middleware as it avoids bugs and also makes the code easier to read.

// Middleware to handle secured route for HTTP GET and HTTP POST
app.use("/secured", twilio.webhook({
  authToken: process.env.TWILIO_AUTH_TOKEN
}), (req, res, next) => {
  console.log("This is a secured route");
  res.header('Content-Type', 'text/xml');
  res.send("<Response><Message>This route is secured</Message></Response>")
});