Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 3 min read

Receive inbound email in Next.js with a webhook

Receive inbound email in Next.js with a webhook This guide wires a Next.js App Router route to ReceiveHQ so inbound mail on your domain arrives as JSON. ReceiveHQ posts a Postmark-format body (application/json) when th

Receive inbound email in Next.js with a webhook

This guide wires a Next.js App Router route to ReceiveHQ so inbound mail on your domain arrives as JSON. ReceiveHQ posts a Postmark-format body (application/json) when the endpoint's payloadFormat is postmark β€” the default.

1. Create the ReceiveHQ endpoint

  1. Sign up at receivehq.com (magic link).
  2. Create a tenant, add an inbound domain, and point MX at mx.receivehq.com.
  3. Create a webhook endpoint:
    • HTTPS URL, for example https://yourapp.com/api/inbound
    • Format: Postmark (JSON) (payloadFormat id postmark)
    • Optional Basic auth, configured on the endpoint (console, or basicAuthUser / basicAuthPass on the MCP create_endpoint / create_inbound_domain_endpoint tools). ReceiveHQ then sends Authorization: Basic <base64(user:pass)> on each POST.
  4. Send a test message and inspect the delivery in the console.

2. What the POST looks like

  • Method: POST
  • Content-Type: application/json
  • User-Agent: receivehq-inbound/1.0
  • Optional Authorization as above

ReceiveHQ does not send provider HMAC headers (no X-Postmark-Signature). Authenticate with HTTPS plus Basic auth, or your own shared-secret query or path scheme.

Documented JSON fields include From (bare email address β€” use FromFull.Name for the display name), FromName, To, OriginalRecipient, Subject, MessageID (no surrounding angle brackets, or a generated UUID), TextBody, HtmlBody, Attachments (each with base64 Content, plus Name, ContentType, ContentLength, ContentID), Headers, and RawEmail. See the field tables for the rest (ToFull, MailboxHash, StrippedTextReply, and others). StrippedTextReply is best-effort and not identical to Postmark's stripper.

3. Route handler

app/api/inbound/route.ts (or src/app/api/inbound/route.ts). Return 2xx once you have accepted the message β€” that is the success code. Return 406 only if you want ReceiveHQ to drop the message with no further retries. Any other status is retried with backoff (1m β†’ 5m β†’ 30m β†’ 1h β†’ 2h), up to the endpoint's maxAttempts setting.

Return 2xx as soon as the message is accepted, and do slower work (disk, attachments, RawEmail) in the background.

import { NextResponse } from "next/server";
import { timingSafeEqual } from "node:crypto";

export const runtime = "nodejs";

type Attachment = {
  Name: string;
  Content: string; // base64
  ContentType: string;
  ContentLength: number;
  ContentID: string | null;
};

type PostmarkInbound = {
  From: string;
  FromName: string;
  To: string;
  OriginalRecipient: string;
  Subject: string;
  MessageID: string;
  TextBody: string;
  HtmlBody: string;
  Attachments: Attachment[];
};

function credsMatch(got: string, expected: string): boolean {
  const a = Buffer.from(got);
  const b = Buffer.from(expected);
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

function checkBasicAuth(req: Request): boolean {
  const user = process.env.INBOUND_BASIC_USER ?? "";
  const pass = process.env.INBOUND_BASIC_PASS ?? "";
  if (!user && !pass) return true; // no Basic auth configured
  const header = req.headers.get("authorization") ?? "";
  const [scheme, encoded] = header.split(" ");
  if (scheme !== "Basic" || !encoded) return false;
  const decoded = Buffer.from(encoded, "base64").toString("utf8");
  const sep = decoded.indexOf(":");
  if (sep < 0) return false;
  return credsMatch(decoded.slice(0, sep), user) && credsMatch(decoded.slice(sep + 1), pass);
}

export async function POST(req: Request) {
  if (!checkBasicAuth(req)) {
    return new NextResponse("Unauthorized", { status: 401 });
  }

  let body: PostmarkInbound;
  try {
    body = (await req.json()) as PostmarkInbound;
  } catch {
    // 4xx other than 406 is retried. 400 is reasonable for a malformed body
    // you never expect from ReceiveHQ; use 406 only to drop a message for good.
    return new NextResponse("Invalid JSON", { status: 400 });
  }

  // Persist or enqueue using MessageID as an idempotency key (retries happen).
  console.log(body.MessageID, body.From, body.Subject, body.Attachments?.length ?? 0);

  return new NextResponse(null, { status: 204 });
}

Set INBOUND_BASIC_USER and INBOUND_BASIC_PASS in the deployment environment to the same values you configured on the ReceiveHQ endpoint. If you leave both unset, the sample skips the auth check β€” do not do that in production.

A 401 is not a 2xx and is not 406, so a misconfigured password will be retried on the documented backoff. That is usually what you want until the secret is fixed.

Further reading

If you want inbound mail as a webhook without running a mail server, ReceiveHQ accepts SMTP on your domain and POSTs Postmark-format JSON to a Next.js route like this one.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.