Unauthorized Nylas Request

I set up Nylas webhooks endpoint in my NodeJS backend application.
And I followed the documents to implement Nylas verification middleware.
However 3 out of 20 webhook requests from Nylas are unauthorized, even though the requests contain related data some of the webhook requests are not verified!

try {
    const signature = req.headers['x-nylas-signature'];
    const webhookSecret = process.env.WEBHOOK_SECRET;

    const digest = crypto
      .createHmac('sha256', webhookSecret)
      .update(JSON.stringify(req.body))
      .digest('hex');

    if (digest === signature) return next();
    console.error('Unauthorized nylas webhook request', {
      grantId: req.body?.data?.grant_id,
      eventId: req.body?.data?.object?.id
    });
    res.status(200).end();
  } catch (err) {
    console.error('Nylas validation failed with error:', err.message);
    res.status(200).end();
  }

Why do I use JSON.stringify(req.body) because req.rawBody is undefined in my case and without parsing req.body try/catch is failing!

I need support!

Hello,

JSON.stringify(req.body) doesn’t reproduce the exact original bytes Nylas used to generate the signature. Key ordering, whitespace, and number formatting can differ.

Capture the raw body before JSON parsing:

// Configure Express to preserve raw body
app.use(
  express.json({
    verify: (req, res, buf) => {
      req.rawBody = buf;
    }
  })
);

// In your verification middleware
const digest = crypto
  .createHmac('sha256', webhookSecret)
  .update(req.rawBody)  // Use raw buffer, not JSON.stringify
  .digest('hex');

if (digest === signature) return next();

req.rawBody is undefined because it doesn’t exist by default. You need to configure Express to save it before parsing.

The verify callback runs before JSON parsing, giving you access to the original bytes. Without this configuration, rawBody simply doesn’t exist.

If you’re using a framework like NestJS or have middleware ordering issues, make sure this express.json() configuration is applied before any other body parsers.

Many thanks,
Samuel R.
Support Engineer, Nylas

1 Like

Hello Samuel,

Thank you for the support, I applied these changes and will be deploying!
As soon as I start monitor the logs I will reply here whether the changes worked or not!

1 Like

Thanks Samuel, after the monitoring I can confirm that the approach worked as we wanted!
Great support!