AssertInbox

Check every link in an email

An email can look right and still send people to the wrong place: a link built from a staging host, a localhost address left in a template, a plain http: link, or a button whose target now returns 404. A test that reads the email and visits every link catches these before your users do. This guide shows a node:test file that waits for a real email through AssertInbox, takes the extracted links, checks their shape, and requests the links that belong to your own app.

What the test checks

AssertInbox returns links for every message: all http and https links from the HTML and text parts, in order, without duplicates (at most 50). That list is the input. The test makes three kinds of assertions:

Get an API key

Get one in a click at /start. One request creates a key and your private namespace, with no email address or card. The key is shown once, so keep it in your secret store and export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page, and the client files can replace the helper functions below.

The test file

Save this as email-links.test.js and run it with node --test on Node 18 or newer. The sign-up route is a placeholder for your own API. Set OWN_HOSTS to a comma-separated list of the hosts your emails should link to, and FORBIDDEN_HOSTS to host fragments that must never appear, such as staging. Use it only against an app you own.

const { test, after } = require("node:test");
const assert = require("node:assert");

const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
const APP = process.env.APP_URL || "http://localhost:3000";
const OWN_HOSTS = (process.env.OWN_HOSTS || new URL(APP).host).split(",");
const FORBIDDEN_HOSTS = (process.env.FORBIDDEN_HOSTS || "staging,preview").split(",");
const ALLOW_THIRD_PARTY = (process.env.ALLOW_THIRD_PARTY || "").split(",").filter(Boolean);
const LINK_TIMEOUT_MS = 10000;

const tags = [];

function newInbox() {
  const tag = ("links-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8)).toLowerCase();
  tags.push(tag);
  return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}

async function waitForEmail(tag, filters = {}) {
  const params = new URLSearchParams({ tag, timeout: "25", ...filters });
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = await fetch(API + "/v1/wait?" + params, {
      headers: { Authorization: "Bearer " + KEY },
    });
    if (res.status === 200) return res.json();
    if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
  }
  throw new Error("No email arrived for tag " + tag);
}

function isIp(hostname) {
  return /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.includes(":");
}

function isOwn(url) {
  return OWN_HOSTS.includes(url.host);
}

async function checkReachable(url) {
  const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(LINK_TIMEOUT_MS) });
  await res.arrayBuffer();
  return res.status;
}

after(async () => {
  for (const tag of tags) {
    await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
      method: "DELETE",
      headers: { Authorization: "Bearer " + KEY },
    });
  }
});

test("every link in the welcome email is safe and own links work", { timeout: 180000 }, async () => {
  const inbox = newInbox();
  const res = await fetch(APP + "/api/signup", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ email: inbox.email, password: "correct-Horse-battery-1" }),
  });
  assert.ok(res.ok, "sign-up returned " + res.status);

  const mail = await waitForEmail(inbox.tag);
  assert.ok(mail.links.length > 0, "the email has no links");

  const problems = [];
  for (const raw of mail.links) {
    const url = new URL(raw);
    const local = OWN_HOSTS.some((h) => h.startsWith("localhost"));
    if (url.protocol !== "https:" && !local) problems.push("not https: " + raw);
    if (!local && (url.hostname === "localhost" || isIp(url.hostname))) problems.push("local or IP host: " + raw);
    if (!local && FORBIDDEN_HOSTS.some((f) => url.hostname.includes(f))) problems.push("forbidden host: " + raw);
  }
  assert.deepStrictEqual(problems, []);

  for (const raw of mail.links) {
    const url = new URL(raw);
    if (!isOwn(url) && !ALLOW_THIRD_PARTY.includes(url.host)) continue;
    if (/unsubscribe|opt-out|optout/i.test(raw)) continue;
    const status = await checkReachable(raw);
    assert.ok(status < 400, raw + " answered " + status);
  }
});

Run it with the key in the environment:

export ASSERTINBOX_KEY=ai_your_key_here
export ASSERTINBOX_NAMESPACE=your_namespace
APP_URL=https://staging.example.com OWN_HOSTS=staging.example.com FORBIDDEN_HOSTS=localhost-only node --test email-links.test.js

Why unsubscribe and tracking links need care

A GET request is supposed to be safe, but email links often are not. Some senders unsubscribe the reader on a plain GET, some confirmation links are single-use, and a tracking redirect may record an open or a click. Requesting them from a test can unsubscribe your test user, consume the very token that a later step needs, or pollute your analytics. That is why the test skips anything that looks like an unsubscribe link. Treat the same way any link that performs an action: a one-time sign-in link, an "approve" button, an invitation acceptance. Test those in their own flow, once, with a browser test; see the guides on the List-Unsubscribe header and password reset emails.

Production mail and staging mail

The shape checks are most valuable when the test runs against the environment that sends real customer mail, for example a smoke test after each release. The same file works against staging if you put the staging host in OWN_HOSTS; the forbidden-host check should then list hosts that must not leak into the mail, such as the production host in a staging email. Choose the lists that fit your setup; the defaults here are only examples.

Limits of this check

Troubleshooting

Next steps

For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.