Browse the docs
By language
Receive email in Node.js
Receive and process inbound email in Node.js with Express: get each message as a signed webhook, verify it, and save its attachments.
This guide builds an Express server that receives every email sent to your
domain, verifies it came from Inboundr, and saves its attachments. It uses only
Node's built-in crypto, with no SDK. Node 18 or later.
Before you start#
- An address to receive on. Your account comes with an
instant domain such as
amber-falcon-4821.inboundr.email, so any address on it works without DNS setup. A verified domain of your own works the same way. - An API key, from API keys in the console:
bash export INBOUNDR_API_KEY="inb_xxxxxxxxxxxxxxxxxxxxxxxx" - A public HTTPS URL for your handler. Inboundr only delivers to public
addresses, so while developing, expose your local port with a tunnel:
bash ngrok http 3000 # or: cloudflared tunnel --url http://localhost:3000
1. Create an endpoint and route mail to it#
An endpoint is the URL Inboundr POSTs each email to. Create one pointing at your tunnel:
curl https://inboundr.net/api/v1/endpoints \
-H "Authorization: Bearer $INBOUNDR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "Local handler", "url": "https://<your-tunnel>/webhooks/inboundr" }'The response includes a secret (whsec_…). It's shown only once, so store it
next to your API key:
export INBOUNDR_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxxxxxxxxxxxxx"Then send the domain's mail to the endpoint. Find the domain's ID (the instant
domain is the one with "managed": true) and set it as the catch-all:
curl https://inboundr.net/api/v1/domains \
-H "Authorization: Bearer $INBOUNDR_API_KEY"
curl -X PATCH https://inboundr.net/api/v1/domains/dom_123 \
-H "Authorization: Bearer $INBOUNDR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "catchAllEndpointIds": ["ep_123"] }'To route a single address instead, see addresses.
2. Write the handler#
npm install expressThe handler gets the parsed message as JSON: from, to, recipients,
subject, text, html, attachment metadata and the spam, SPF and DKIM
verdicts. See the full payload. Read the body raw, because the signature covers its exact
bytes:
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
const SECRET = process.env.INBOUNDR_WEBHOOK_SECRET;
const API_KEY = process.env.INBOUNDR_API_KEY;
/** Checks X-Inboundr-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">. */
function verifySignature(rawBody, header) {
if (!header) return false;
const parts = Object.fromEntries(
header.split(",").map((kv) => {
const i = kv.indexOf("=");
return [kv.slice(0, i), kv.slice(i + 1)];
}),
);
const t = Number(parts.t);
// Reject old deliveries so a captured request can't be replayed.
if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
const expected = createHmac("sha256", SECRET)
.update(`${parts.t}.`)
.update(rawBody)
.digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(parts.v1 ?? "");
return a.length === b.length && timingSafeEqual(a, b);
}
// Use your database in production: this forgets everything on restart.
const handled = new Set();
const app = express();
app.post(
"/webhooks/inboundr",
express.raw({ type: "application/json", limit: "64mb" }),
(req, res) => {
if (!verifySignature(req.body, req.get("x-inboundr-signature"))) {
return res.status(401).send("invalid signature");
}
const { email } = JSON.parse(req.body.toString("utf8"));
// Retries keep their delivery ID. Recorded only after parsing succeeded,
// so a delivery that failed here is processed when it's retried.
const deliveryId = req.get("x-inboundr-delivery-id");
if (deliveryId) {
if (handled.has(deliveryId)) return res.sendStatus(200);
handled.add(deliveryId);
}
// Acknowledge first, then work: slow handlers time out and get retried.
res.sendStatus(200);
processEmail(email).catch((err) => console.error("processing failed", err));
},
);
async function processEmail(email) {
console.log(`${email.from} → ${email.recipients.join(", ")}: ${email.subject}`);
await mkdir("attachments", { recursive: true });
for (const [i, attachment] of email.attachments.entries()) {
if (!attachment.downloadUrl) continue; // not stored on this plan
const res = await fetch(attachment.downloadUrl, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!res.ok) throw new Error(`download failed: ${res.status}`);
// Inline images often have no filename, and two can share one, so the
// index keeps them apart. basename: never trust a sender's name as a path.
const name = path.basename(attachment.filename ?? `attachment-${i}`);
const file = path.join("attachments", `${email.id}-${i}-${name}`);
await writeFile(file, Buffer.from(await res.arrayBuffer()));
console.log(`saved ${file}`);
}
}
app.listen(3000, () => console.log("listening on :3000"));node server.mjsMount express.raw on this route only, and before any global
express.json(). If JSON parsing runs first, the original bytes are gone and
every signature check fails.
3. Test it#
Send a sample delivery. It's signed with your endpoint's real secret, so it also tests your signature check:
curl -X POST https://inboundr.net/api/v1/endpoints/ep_123/test \
-H "Authorization: Bearer $INBOUNDR_API_KEY""ok": true means your handler answered with a 2xx. A 401 in status
means the signature didn't match: see troubleshooting.
Then send a real email, with an attachment, from your own mailbox to any
address on your domain, such as test@amber-falcon-4821.inboundr.email. It
reaches your handler within seconds.
Read mail without a server#
Webhooks need a public URL. For scripts, cron jobs and agents, read the inbox on demand instead. Mail is stored either way:
const res = await fetch(
"https://inboundr.net/api/v1/emails?direction=inbound&limit=20",
{ headers: { Authorization: `Bearer ${process.env.INBOUNDR_API_KEY}` } },
);
const { data, nextCursor } = await res.json();
for (const email of data) {
console.log(email.receivedAt, email.fromAddress, email.subject);
}Fetch one message in full with GET /v1/emails/{id}. Pass nextCursor back
as cursor for the next page. See the emails API.
Troubleshooting#
- Every delivery fails the signature check. The HMAC is computed over the
exact bytes sent. Read the raw body before any JSON parsing, and don't
re-serialize it. Also check you're using the endpoint's
whsec_…secret, not yourinb_API key. - Deliveries time out. Your handler has 30 seconds by default. Acknowledge first, then do slow work (AI calls, downloads, database writes) in the background.
- The same email arrives twice. A delivery is retried when your handler
doesn't answer
2xxin time, and a retry keeps itsX-Inboundr-Delivery-Id. Store handled IDs and skip repeats. - The body is empty. Some hosts drop request bodies. Every delivery also carries the email's ID with its own signature, so you can fetch it instead: see when the body is missing.
- Nothing arrives. Check the email under Emails in the console. If it's there, open its delivery to see your handler's response. If it isn't, the message never reached Inboundr: check the address and, for your own domain, its MX record.