Receive Email Webhooks in Express

Complete guide to integrating JsonHook with Express (JavaScript). Working code examples for webhook handling, signature verification, and payload parsing.

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

Quick Start: Express Email Webhook

JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Express 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();

// Raw body parser on webhook route only
app.use('/webhook', express.raw({ type: 'application/json' }));

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

app.listen(3000, () => console.log('Express webhook server on :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 Express 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 SECRET = process.env.JSONHOOK_WEBHOOK_SECRET;

// Apply raw body parser ONLY to the webhook route
app.use('/webhook', express.raw({ type: 'application/json' }));

// Apply JSON parser to all other routes
app.use(express.json());

function verifySignature(rawBody, sigHeader) {
  if (!sigHeader) return false;
  const computed = crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex');
  try {
    return crypto.timingSafeEqual(
      Buffer.from(computed, 'hex'),
      Buffer.from(sigHeader, 'hex')
    );
  } catch { return false; }
}

app.post('/webhook', (req, res) => {
  const sig = req.headers['x-jsonhook-signature'];
  if (!verifySignature(req.body, sig)) {
    return res.sendStatus(401);
  }

  const payload = JSON.parse(req.body);
  // Respond immediately, process later
  res.sendStatus(200);

  setImmediate(() => {
    const { email, address, timestamp } = payload;
    console.log(`[${timestamp}] ${address}: ${email.from} — ${email.subject}`);
    for (const att of email.attachments || []) {
      console.log(`  Attachment: ${att.filename} (${att.size} bytes)`);
    }
  });
});

// Example: other routes still use JSON middleware normally
app.get('/health', (req, res) => res.json({ status: 'ok' }));

app.listen(3000, () => console.log('Listening on :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 Express 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:

// req.body is a Buffer when using express.raw()
const payload = JSON.parse(req.body);

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

const { from, to, subject, textBody, htmlBody, attachments } = email;
// from:        "Alice "
// to:          ["[email protected]"]
// subject:     "Hello"
// textBody:    "Plain text..."
// htmlBody:    "

HTML...

" // attachments: [{ filename, contentType, size, contentId }]

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 verifySignature(rawBody, sigHeader, secret) {
  if (!sigHeader || !secret) return false;
  const computed = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  try {
    return crypto.timingSafeEqual(
      Buffer.from(computed, 'hex'),
      Buffer.from(sigHeader, 'hex')
    );
  } catch { return false; }
}

// In your Express route:
// app.use('/webhook', express.raw({ type: 'application/json' }));
// app.post('/webhook', (req, res) => {
//   if (!verifySignature(req.body, req.headers['x-jsonhook-signature'], SECRET)) {
//     return res.sendStatus(401);
//   }
//   ...
// });

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.

Express-specific tips:

  • Mount express.raw({ type: 'application/json' }) as route-level middleware on '/webhook', not at the app level — mixing it with express.json() globally causes both to fire and the second will fail
  • Use setImmediate() or process.nextTick() for trivial deferred work; use BullMQ or a similar job queue for any work that involves I/O or can fail
  • Add an Express error handler (app.use((err, req, res, next) => ...)) as the last middleware to catch synchronous throws and return 500, which causes JsonHook to retry
  • Test your webhook locally with ngrok http 3000 or similar before pointing a live JsonHook address at it

Express Framework Tips

Express provides several conveniences that make webhook handling cleaner. Here are framework-specific patterns to use when integrating JsonHook:

  • Register your webhook route before any authentication middleware — the JsonHook request does not carry user credentials, only the HMAC signature.
  • Use raw body access for signature verification. Many Express frameworks parse the body automatically — make sure you are hashing the raw bytes, not the re-serialized parsed object.
  • Use a dedicated route or controller file for webhook handlers to keep the codebase organized as you add more inbound address integrations.
  • Log the address field from every payload to track which inbound address received the email — useful for multi-address setups.
  • Consider using Express's built-in request validation or a schema library (e.g., Zod, Pydantic, etc.) to validate the payload structure after signature verification.

Frequently Asked Questions

How do I receive JsonHook webhooks in Express?
Create an HTTP endpoint in your Express 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 Express?
Yes. JsonHook works with any HTTP server that can receive POST requests — Express 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 Express?
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 Express?
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 Express, 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.