Quick Start: NestJS Email Webhook
JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a NestJS handler takes less than 5 minutes. Start by initializing your project:
npm i -g @nestjs/cli && nest new webhook-app && cd webhook-app
Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:
// webhook.controller.ts
import { Controller, Post, Req, Res, HttpCode } from '@nestjs/common';
import { Request, Response } from 'express';
@Controller()
export class WebhookController {
@Post('webhook')
@HttpCode(200)
async receive(@Req() req: Request, @Res() res: Response) {
const payload = JSON.parse(req.body);
console.log('From:', payload.email.from, '| Subject:', payload.email.subject);
res.sendStatus(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 NestJS 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.controller.ts
import {
Controller, Post, Req, Res, Headers, HttpCode, Logger
} from '@nestjs/common';
import { Request, Response } from 'express';
import * as crypto from 'crypto';
const WEBHOOK_SECRET = process.env.JSONHOOK_WEBHOOK_SECRET!;
function verifySignature(rawBody: Buffer, sigHeader: string): boolean {
if (!sigHeader) return false;
const computed = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(computed, 'hex'),
Buffer.from(sigHeader, 'hex')
);
} catch { return false; }
}
@Controller()
export class WebhookController {
private readonly logger = new Logger(WebhookController.name);
@Post('webhook')
async receive(
@Req() req: Request,
@Res() res: Response,
@Headers('x-jsonhook-signature') sig: string
) {
const rawBody = req.body as Buffer;
if (!verifySignature(rawBody, sig)) {
this.logger.warn('Invalid signature');
return res.sendStatus(401);
}
let payload: any;
try { payload = JSON.parse(rawBody.toString('utf-8')); }
catch { return res.sendStatus(400); }
res.sendStatus(200); // Respond immediately
const { email, address, timestamp } = payload;
this.logger.log(`[${timestamp}] ${address}: ${email.from} — ${email.subject}`);
for (const att of email.attachments ?? []) {
this.logger.log(` Attachment: ${att.filename} (${att.size} bytes)`);
}
}
}
// main.ts — enable raw body for NestJS:
// app.use('/webhook', express.raw({ 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 NestJS Email Integration
Free API key — start receiving webhooks in 5 minutes.
Get Free API KeyParsing 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:
// rawBody is a Buffer (from express.raw() middleware)
const rawStr = rawBody.toString('utf-8');
const payload = JSON.parse(rawStr);
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, andcontentId
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 * as crypto from 'crypto';
function verifyJsonHookSignature(rawBody: Buffer, sigHeader: string, secret: string): boolean {
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; }
}
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.
NestJS-specific tips:
- Register
express.raw({ type: 'application/json' })for the/webhookpath inmain.tsbeforeapp.listen()— NestJS uses Express under the hood and needs raw body access for HMAC - Use
@Headers('x-jsonhook-signature')to inject the signature header into your controller method rather than reading fromreq.headersmanually - Use NestJS's built-in
EventEmitter2module or@nestjs/bullto process email payloads asynchronously after sending the 200 response - Register a NestJS exception filter (
@Catch()) to return structured JSON error responses on unhandled exceptions, ensuring 500s trigger JsonHook retries
NestJS Framework Tips
NestJS 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 NestJS 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
addressfield from every payload to track which inbound address received the email — useful for multi-address setups. - Consider using NestJS's built-in request validation or a schema library (e.g., Zod, Pydantic, etc.) to validate the payload structure after signature verification.