AssertInbox

Magic-link login in Cypress: wait for the email, then visit the link

A magic link replaces the password: the user enters an address, the app emails a one-time link, and opening the link signs them in. In a Cypress test, the hard part is the email. Cypress runs your spec in the browser, but anything that needs the network outside the page, or secrets that should not be in the browser, belongs in a task, which runs in Node. This guide builds one task that waits for the message and returns the link, then uses cy.visit to open it. It targets Cypress 12 or newer, where cy.origin is available, and it uses no plugins.

How it works

Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. The tag is the isolation boundary: every test builds its own tag, so tests never read each other's mail. A task is a good place for the wait because the 25-second long poll then never runs into a browser command timeout.

Get an API key

Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your secret manager or CI secrets.

curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}

Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page.

Pass the key to the task

Tasks run in the Node process that started Cypress, so they can read process.env directly and the key never reaches the browser bundle. Register the task in cypress.config.js. It needs Node 18 or newer for the built-in fetch.

const { defineConfig } = require("cypress");

const API = "https://assertinbox.com";

module.exports = defineConfig({
  e2e: {
    baseUrl: process.env.APP_URL || "http://localhost:3000",
    setupNodeEvents(on) {
      on("task", {
        async waitForMagicLink({ tag, subject }) {
          const params = new URLSearchParams({ tag, timeout: "25" });
          if (subject) params.set("subject", subject);
          for (let attempt = 0; attempt < 3; attempt++) {
            const res = await fetch(API + "/v1/wait?" + params, {
              headers: { Authorization: "Bearer " + process.env.ASSERTINBOX_KEY },
            });
            if (res.status === 200) {
              const mail = await res.json();
              if (!mail.magic_link) throw new Error("Email for tag " + tag + " has no magic link");
              return mail.magic_link;
            }
            if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status + " for tag " + tag);
          }
          throw new Error("No email arrived for tag " + tag);
        },
        async deleteEmails(tag) {
          await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
            method: "DELETE",
            headers: { Authorization: "Bearer " + process.env.ASSERTINBOX_KEY },
          });
          return null;
        },
      });
    },
  },
});

A task must return a value or null; returning undefined makes Cypress fail it, which is why deleteEmails returns null. Cypress also gives a task its own timeout, taskTimeout, which defaults to 60 seconds. Three polls of 25 seconds fit in 75 seconds, so raise it if you want all three attempts: set taskTimeout: 90000 in the e2e block.

The spec

Save this as cypress/e2e/magic-link.cy.js. Replace the field names, button text and the final assertion with those of your app. The address is built in the spec from your namespace and a unique tag, so it needs the namespace as a Cypress environment variable: set CYPRESS_ASSERTINBOX_NAMESPACE in your shell or CI.

describe("magic-link login", () => {
  it("signs in through the emailed link", () => {
    const tag = ("cy-magic-" + Date.now() + "-" + Math.random().toString(36).slice(2, 6)).toLowerCase();
    const email = Cypress.env("ASSERTINBOX_NAMESPACE") + "." + tag + "@assertinbox.com";

    cy.visit("/login");
    cy.get("input[name=email]").type(email);
    cy.contains("button", "Email me a link").click();
    cy.contains("Check your inbox").should("be.visible");

    cy.task("waitForMagicLink", { tag, subject: "sign in" }).then((link) => {
      cy.visit(link);
    });

    cy.contains("Dashboard").should("be.visible");
    cy.task("deleteEmails", tag);
  });
});

Because cy.task is queued like any other Cypress command, the order is the order you read: submit the form, wait in Node, then visit the link. Do not wrap it in async and await, which Cypress commands do not support.

The same-origin rule

Cypress controls the browser by running your test inside the page's origin. Before Cypress 12 a test could not visit two origins in a single test. From version 12 this restriction is gone, but you now need to tell Cypress when a block of commands runs on a different origin, using cy.origin.

In the spec above the link points at your own app, which is the same origin as baseUrl, so a plain cy.visit(link) and normal commands are enough. The link may also be an absolute URL: that works as long as the host matches your app. If your staging mail contains production links, replace the host before visiting, for example by building a URL from Cypress.config("baseUrl") and the path and query of the link.

When the link goes through another domain

Some apps send a link to a tracking or identity domain, which then redirects to your app. If the final page is on a different origin from baseUrl, the commands that run there must be inside cy.origin. The Cypress documentation describes the details, including that values from outside the callback must be passed in through the args option. A sketch:

describe("magic link through an identity domain", () => {
  it("lands on the app after the redirect", () => {
    const tag = ("cy-origin-" + Date.now()).toLowerCase();
    const email = Cypress.env("ASSERTINBOX_NAMESPACE") + "." + tag + "@assertinbox.com";

    cy.visit("/login");
    cy.get("input[name=email]").type(email);
    cy.contains("button", "Email me a link").click();

    cy.task("waitForMagicLink", { tag }).then((link) => {
      const host = new URL(link).origin;
      cy.origin(host, { args: { link } }, ({ link }) => {
        cy.visit(link);
        cy.contains("button", "Continue").click();
      });
    });

    cy.contains("Dashboard").should("be.visible");
    cy.task("deleteEmails", tag);
  });
});

After the redirect returns to baseUrl, commands outside cy.origin work again. If the identity page is not something you control, consider skipping it: ask the app's test environment for a link that goes straight to your domain, or test the redirect separately.

Cleaning up and running in CI

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: Cypress OTP login, Auth.js magic link and Playwright email verification. The wait filters are described in the docs, and the client files wrap the helper for Node.js and Python.

Free beta, run by AI agents

This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.