How to test magic link login end to end

Last updated 2026-12-03 · By the Humanless team at Ninety Nine Oranges · Markdown version

Short answer: Send the magic link to an inbox your test can read, extract the sign-in URL from the email, and open it with page.goto(url) in the same browser context that requested it, then assert that you are logged in. The hard parts are picking the right link out of an email full of links, PKCE or state cookies that tie the link to the requesting browser, single-use tokens that expire, and links that point at the wrong host. With Humanless, waitForLink returns the sign-in URL already extracted.

Use policy: These techniques are for testing login on applications you own or are authorized to test. See the Terms.

The end-to-end flow

  1. Create (or reuse) a test user with an address your test can read.
  2. On the login page, submit the email address. Record the time just before you click.
  3. Wait for the email and extract the sign-in URL.
  4. await page.goto(url) in the same page or browser context.
  5. Assert the logged-in state, such as an avatar, a dashboard heading or a session cookie.

Option 1: Mailpit locally

With your app's SMTP pointed at Mailpit (see the email OTP guide), read the newest message for the address and pull the link out of the HTML. Match your own auth route, not "the first link", because emails also contain logo, help and unsubscribe links:

mailpit-link.ts
import { expect } from "@playwright/test";

export async function mailpitMagicLink(to: string): Promise<string> {
  let link = "";
  await expect
    .poll(async () => {
      const q = encodeURIComponent(`to:"${to}"`);
      const { messages } = await (await fetch(`http://localhost:8025/api/v1/search?query=${q}`)).json();
      if (!messages?.length) return "";
      const msg = await (await fetch(`http://localhost:8025/api/v1/message/${messages[0].ID}`)).json();
      const href = msg.HTML.match(/href="([^"]*\/auth\/verify[^"]*)"/)?.[1] ?? "";
      link = href.replaceAll("&amp;", "&"); // hrefs in HTML are entity-encoded
      return link;
    }, { timeout: 30_000 })
    .not.toBe("");
  return link;
}

Option 2: Humanless, against any environment

waitForLink waits for a message that contains a sign-in link and returns it as url. Humanless picks the link by scoring words like "sign in", "verify" and "confirm" in the link text and URL. It skips unsubscribe, help, social and image links and decodes HTML entities, so you get a URL you can navigate to directly:

magic-link.spec.ts
import { expect, test } from "@playwright/test";
import { Humanless, withIdentity } from "./humanless"; // TypeScript SDK, one file: usehumanless.com/sdk/humanless.ts

const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! });

test("log in with a magic link", async ({ page }) => {
  await withIdentity(hl, { channels: ["email"] }, async ({ identity_id, email }) => {
    await page.goto("http://localhost:3000/login");
    await page.getByLabel("Email").fill(email!);
    const requestedAt = Date.now();
    await page.getByRole("button", { name: "Email me a sign-in link" }).click();

    const { url } = await hl.waitForLink({ identityId: identity_id, since: requestedAt, timeout: 25 });
    await page.goto(url); // same page, same context: PKCE verifier and cookies are still here
    await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
  });
});

Over REST, the same message comes back from GET /v1/identities/:id/wait with "type": "magic_link" and the link in url. Emails that contain both a code and a link come back as "type": "otp" with both code and url set.

Pitfalls

FAQ

How do I test magic link login in Playwright?

Submit the login form with an address your test controls, wait for the email, extract the sign-in URL and call page.goto(url) in the same page, then assert the logged-in UI. With Humanless the whole wait-and-extract step is const { url } = await hl.waitForLink({ identityId, since }).

Why does my magic link say "invalid" or "expired" in tests?

Usually one of three things: the link was opened in a different browser context than the one that requested it (PKCE or state mismatch), it was already used or a newer link replaced it, or it expired before the test opened it. Open it in the same page, request it once, and open it right away.

How do I find the right link in the email?

Match your own auth path (for example /auth/verify or /auth/callback) in the HTML and decode &amp; in the href. Or use a service that extracts it for you: Humanless returns the most likely sign-in link as url, and hosted testing tools like Mailosaur also return the links they find in a message (see their docs).

Can I test magic links in Cypress too?

Yes. The Humanless REST API and SDK are framework-agnostic. Call them from a Cypress task (cy.task) in Node, then cy.visit(url). Cypress keeps one browser session per test, so the same-context rule is easy to satisfy.

Does Humanless click the link for me?

No. It only receives and parses the email. Your test or agent opens the URL, which is what makes the test meaningful.

Humanless: disposable inboxes, dedicated US SMS numbers and TOTP for testing apps you own. Email and TOTP are free.

Get an API key