Receive Email Webhooks in Deno

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

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

Quick Start: Deno Email Webhook

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

# Install Deno: curl -fsSL https://deno.land/install.sh | sh
# No package manager needed — Deno imports from URLs

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

// webhook.ts
import { createHmac } from "node:crypto";

Deno.serve({ port: 3000 }, async (req: Request) => {
  if (req.method !== "POST" || new URL(req.url).pathname !== "/webhook") {
    return new Response("Not Found", { status: 404 });
  }

  const payload = await req.json();
  console.log("Email from:", payload.email.from);
  console.log("Subject:", payload.email.subject);
  return new Response("ok", { status: 200 });
});

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 Deno 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.

// webhook.ts
// Run with: deno run --allow-net --allow-env webhook.ts
import { createHmac, timingSafeEqual } from "node:crypto";

const WEBHOOK_SECRET = Deno.env.get("JSONHOOK_WEBHOOK_SECRET") ?? "";

interface Attachment {
  filename: string;
  contentType: string;
  size: number;
  contentId: string;
}

interface JsonHookPayload {
  event: string;
  timestamp: string;
  address: string;
  email: {
    from: string;
    to: string[];
    subject: string;
    textBody: string;
    htmlBody: string;
    attachments: Attachment[];
  };
}

function verifySignature(rawBody: string, sigHeader: string | null): boolean {
  if (!sigHeader || !WEBHOOK_SECRET) return false;
  const computed = createHmac("sha256", WEBHOOK_SECRET)
    .update(rawBody, "utf-8")
    .digest("hex");
  try {
    return timingSafeEqual(
      Buffer.from(computed, "hex"),
      Buffer.from(sigHeader, "hex")
    );
  } catch { return false; }
}

Deno.serve({ port: 3000 }, async (req: Request) => {
  const url = new URL(req.url);
  if (req.method !== "POST" || url.pathname !== "/webhook") {
    return new Response("Not Found", { status: 404 });
  }

  const rawBody = await req.text();
  const sig = req.headers.get("x-jsonhook-signature");

  if (!verifySignature(rawBody, sig)) {
    console.warn("Invalid signature");
    return new Response(JSON.stringify({ error: "Unauthorized" }), {
      status: 401,
      headers: { "Content-Type": "application/json" },
    });
  }

  let payload: JsonHookPayload;
  try { payload = JSON.parse(rawBody); }
  catch {
    return new Response(JSON.stringify({ error: "Bad request" }), {
      status: 400,
      headers: { "Content-Type": "application/json" },
    });
  }

  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)`);
  }

  return new Response(JSON.stringify({ status: "ok" }), {
    status: 200,
    headers: { "Content-Type": "application/json" },
  });
});

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 Deno 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:

const rawBody = await req.text(); // Must call before req.json()
const payload = JSON.parse(rawBody) as JsonHookPayload;

const event     = payload.event;      // "email.received"
const timestamp = payload.timestamp;  // ISO 8601
const address   = payload.address;    // "[email protected]"

const { from, to, subject, textBody, htmlBody, attachments } = payload.email;

for (const att of attachments) {
  console.log(`${att.filename} | ${att.contentType} | ${att.size} bytes`);
}

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.

import { createHmac, timingSafeEqual } from "node:crypto";

function verifyJsonHookSignature(
  rawBody: string,
  sigHeader: string | null,
  secret: string
): boolean {
  if (!sigHeader || !secret) return false;
  const computed = createHmac("sha256", secret)
    .update(rawBody, "utf-8")
    .digest("hex");
  try {
    return timingSafeEqual(
      Buffer.from(computed, "hex"),
      Buffer.from(sigHeader, "hex")
    );
  } catch { return false; }
}

// Usage:
// const rawBody = await req.text();
// const sig = req.headers.get("x-jsonhook-signature");
// if (!verifyJsonHookSignature(rawBody, sig, WEBHOOK_SECRET)) {
//   return new Response("Unauthorized", { status: 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.

Deno ecosystem tips:

  • Use await req.text() to get the raw body string for HMAC verification — calling req.json() first consumes the body stream
  • Deno's node:crypto compatibility layer includes createHmac and timingSafeEqual — no third-party crypto library is needed
  • Run the webhook server with --allow-net --allow-env flags; avoid --allow-all in production to maintain Deno's security model
  • For Deno Deploy deployments, use Deno.KV or a Deno-compatible queue (e.g., Upstash) to defer processing off the request lifecycle

Deno Ecosystem Tips

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