Receive Email Webhooks in Node.js

Complete guide to integrating JsonHook with Node.js. Working code examples for webhook handling, signature verification, and payload parsing.

Table of Contents
  1. Quick Start: Node.js Email Webhook
  2. Full Node.js Implementation
  3. Parsing the Webhook Payload
  4. Verifying Webhook Signatures
  5. Error Handling Best Practices
  6. Node.js Ecosystem Tips

Quick Start: Node.js Email Webhook

JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Node.js handler takes less than 5 minutes. Start by initializing your project:

npm init -y && npm install express

Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:

const express = require('express');
const app = express();

// Use raw body middleware so we can verify the HMAC signature
app.use('/webhook', express.raw({ type: 'application/json' }));

app.post('/webhook', (req, res) => {
  const payload = JSON.parse(req.body);
  console.log('Received email from:', payload.email.from);
  console.log('Subject:', payload.email.subject);
  res.sendStatus(200);
});

app.listen(3000, () => console.log('Listening on port 3000'));

Point your JsonHook address webhook URL to this endpoint and you will start receiving parsed emails as JSON within seconds of the email arriving.

Full Node.js Implementation

The quick start example above is enough to get started, but a production implementation should include signature verification, structured error handling, and proper HTTP response codes. The complete example below demonstrates all of these patterns together.

This implementation verifies the X-JsonHook-Signature header to confirm the request genuinely came from JsonHook, parses the full email payload, and returns the appropriate HTTP status codes to trigger or suppress retries.

const express = require('express');
const crypto = require('crypto');

const app = express();
const WEBHOOK_SECRET = process.env.JSONHOOK_WEBHOOK_SECRET;

// Must use raw body parser to compute HMAC over exact bytes received
app.use('/webhook', express.raw({ type: 'application/json' }));

function verifySignature(rawBody, signatureHeader) {
  if (!signatureHeader) return false;
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(rawBody)
    .digest('hex');
  // Constant-time comparison to prevent timing attacks
  try {
    return crypto.timingSafeEqual(
      Buffer.from(expected, 'hex'),
      Buffer.from(signatureHeader, 'hex')
    );
  } catch {
    return false;
  }
}

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-jsonhook-signature'];

  if (!verifySignature(req.body, signature)) {
    console.warn('Invalid signature — rejecting request');
    return res.sendStatus(401);
  }

  let payload;
  try {
    payload = JSON.parse(req.body);
  } catch {
    return res.sendStatus(400);
  }

  // Acknowledge immediately — process asynchronously
  res.sendStatus(200);

  // Process the email payload
  const { email, address, timestamp } = payload;
  console.log(`[${timestamp}] Email received at ${address}`);
  console.log('From:', email.from);
  console.log('Subject:', email.subject);
  console.log('Text body:', email.textBody);

  if (email.attachments && email.attachments.length > 0) {
    for (const att of email.attachments) {
      console.log(`Attachment: ${att.filename} (${att.contentType}, ${att.size} bytes)`);
    }
  }
});

app.listen(3000, () => console.log('JsonHook webhook server listening on port 3000'));

The webhook handler returns 200 immediately after queuing the email for processing. Avoid doing expensive work (database writes, API calls) synchronously inside the handler — process the payload in a background job to stay within JsonHook's 10-second response timeout.

Build Your Node.js Email Integration

Free API key — start receiving webhooks in 5 minutes.

Get Free API Key

Parsing the Webhook Payload

Every JsonHook delivery is an HTTP POST with Content-Type: application/json. The payload follows a consistent schema regardless of the originating email client or provider:

// JsonHook sends Content-Type: application/json
// After signature verification, parse the raw body:
const payload = JSON.parse(req.body);

// Top-level fields
const event     = payload.event;      // "email.received"
const timestamp = payload.timestamp;  // "2026-03-15T12:34:56.789Z"
const address   = payload.address;    // "[email protected]"

// Email fields
const from      = payload.email.from;      // "Alice "
const to        = payload.email.to;        // ["[email protected]"]
const subject   = payload.email.subject;   // "Hello from Alice"
const textBody  = payload.email.textBody;  // Plain text body
const htmlBody  = payload.email.htmlBody;  // HTML body (may be empty)

// Attachments array
for (const att of payload.email.attachments) {
  console.log(att.filename);    // "report.pdf"
  console.log(att.contentType); // "application/pdf"
  console.log(att.size);        // 204800 (bytes)
  console.log(att.contentId);   // "" or null
}

Key fields in the payload:

  • event — Always "email.received" for inbound email events
  • timestamp — ISO 8601 timestamp of when JsonHook received the email
  • address — The JsonHook inbound address that received the email (e.g., [email protected])
  • email.from — Sender address string, e.g., "Alice <[email protected]>"
  • email.to — Array of recipient address strings
  • email.subject — Email subject line
  • email.textBody — Plain text body of the email (may be empty if HTML-only)
  • email.htmlBody — HTML body of the email (may be empty if plain-text-only)
  • email.attachments — Array of attachment objects, each with filename, contentType, size, and contentId

Verifying Webhook Signatures

JsonHook signs every webhook delivery using HMAC-SHA256. The signature is included in the X-JsonHook-Signature request header as a hex digest. To verify it, compute the HMAC-SHA256 of the raw request body using your address's webhook secret and compare it to the header value.

Your webhook secret is returned when you create an inbound address via the API (POST /api/addresses). Store it as an environment variable — never hard-code it.

const crypto = require('crypto');

function verifyJsonHookSignature(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) return false;
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(rawBody); // rawBody must be Buffer or string of raw bytes
  const computed = hmac.digest('hex');
  try {
    return crypto.timingSafeEqual(
      Buffer.from(computed, 'hex'),
      Buffer.from(signatureHeader, 'hex')
    );
  } catch {
    return false; // Lengths differ — definitely invalid
  }
}

// Usage in Express (requires express.raw() middleware on the route)
app.post('/webhook', (req, res) => {
  const sig = req.headers['x-jsonhook-signature'];
  const secret = process.env.JSONHOOK_WEBHOOK_SECRET;
  if (!verifyJsonHookSignature(req.body, sig, secret)) {
    return res.sendStatus(401);
  }
  // Safe to parse and process
  const payload = JSON.parse(req.body);
  res.sendStatus(200);
});

Always verify the signature before processing the payload. Return 401 for invalid signatures so that legitimate retries from JsonHook (which always include a valid signature) are distinguishable from spoofed requests.

Error Handling Best Practices

Reliable webhook handling requires careful attention to error responses. JsonHook uses your HTTP response code to decide whether to retry a delivery:

  • Return 200 quickly: Acknowledge receipt immediately and process asynchronously. JsonHook will retry any non-2xx response.
  • Return 400 for bad requests: If the payload fails your own validation (not signature — use 401 for that), return 400 to prevent retries of malformed deliveries.
  • Return 500 to trigger retries: If your downstream system is temporarily unavailable, returning 500 causes JsonHook to retry with exponential backoff (up to 5 attempts over ~1 hour).
  • Never return 200 before verifying the signature: Doing so silently accepts spoofed requests.

Node.js ecosystem tips:

  • Use express.raw({ type: 'application/json' }) on the webhook route only — not globally — to avoid breaking other JSON endpoints that use express.json()
  • Wrap JSON.parse(req.body) in a try/catch and return 400 on parse failure to avoid unhandled exceptions crashing the process
  • Use process.nextTick or a job queue (e.g., Bull, BullMQ) to push email processing off the request/response cycle and avoid timeouts
  • Set NODE_ENV=production in your environment to suppress stack traces in error responses sent to external callers

Node.js Ecosystem Tips

The Node.js ecosystem offers several libraries and patterns that pair well with JsonHook webhook handling. Here are general recommendations:

  • Use a well-maintained HTTP server library appropriate for your use case — the examples in this guide use the most common choice, but any library that gives you raw body access works.
  • Store your webhook secret in an environment variable and load it via your language's standard env access pattern — never commit secrets to version control.
  • Use your language's standard HMAC library rather than a third-party package — all languages featured in this guide have HMAC-SHA256 in their standard library.
  • Consider a structured logging library to capture the address, event, and timestamp fields from every webhook delivery for observability.
  • Test your handler locally using a tunneling tool like ngrok or a local webhook testing service before pointing your JsonHook address at a production URL.

Frequently Asked Questions

How do I receive JsonHook webhooks in Node.js?
Create an HTTP endpoint in your Node.js application that accepts POST requests with a JSON body. Register the endpoint URL in your JsonHook inbound address configuration. When email arrives at your JsonHook address, JsonHook will POST the parsed email as JSON to your endpoint. See the complete code example on this page for a production-ready implementation including signature verification.
Does JsonHook work with Node.js?
Yes. JsonHook works with any HTTP server that can receive POST requests — Node.js is fully supported. JsonHook delivers a standard application/json POST with an HMAC-SHA256 signature header. There is no SDK or library required; you use your language or framework's standard HTTP and crypto libraries.
How do I verify webhook signatures in Node.js?
Read the raw request body bytes before any JSON parsing, then compute HMAC-SHA256 of those bytes using your webhook secret as the key. Compare the resulting hex digest to the value of the X-JsonHook-Signature header. Use a constant-time comparison function to prevent timing attacks. Return 401 if the signatures do not match. The full code example is shown in the "Verifying Webhook Signatures" section above.
What does the JsonHook payload look like in Node.js?
The payload is a JSON object with an event string ("email.received"), a timestamp ISO string, an address string (the receiving JsonHook address), and an email object containing from, to, subject, textBody, htmlBody, and attachments. In Node.js, parse it with your standard JSON library and access fields as you would any JSON object. See the "Parsing the Webhook Payload" section for a complete example.