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,waitForLinkreturns 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
- Create (or reuse) a test user with an address your test can read.
- On the login page, submit the email address. Record the time just before you click.
- Wait for the email and extract the sign-in URL.
await page.goto(url)in the samepageor browser context.- 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:
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("&", "&"); // 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:
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
- Open the link in the same browser context. Libraries that use PKCE, or a state or nonce cookie, store a verifier in the browser that requested the link. Opening the link in a fresh context, or in a different browser from a "real" inbox, fails with an invalid or expired link error. Use the same
page. - Single-use and short-lived tokens. Each link usually works once and expires in minutes. Don't open it twice (for example in a debug step and then in the test), and don't make the test wait long before opening it.
- Requesting twice. A second request usually invalidates the first link. Record
Date.now()before the click that sends the email you want, and pass it assince, so you never act on a stale link. - Wrong base URL. Staging emails that link to production, or to
localhostfrom a deployed preview, are a configuration bug in your app's site URL or callback settings, and a test should catch them. Assertnew URL(url).hostif it matters. - Click tracking. Email providers' click tracking wraps links in redirect URLs. Disable click tracking for authentication emails. It also protects your users, because tracking redirects can break single-use links. Humanless can still pick a tracked link by its anchor text, but the URL it returns is the tracking redirect, so your test also depends on the tracker.
- Link prefetching by mail scanners. Corporate email security tools sometimes fetch links in incoming mail, which can consume a single-use token before the user clicks. Your test inbox won't do that (Humanless parses messages and never opens links), but real users' mailboxes might. Consider a confirmation step on the landing page.
- Separate templates for sign-up and sign-in. Many apps send "Confirm your email" on first sign-up and "Sign in" afterwards. Test both.
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 & 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.
Related guides
- How to test email OTP and verification codes in Playwright
- How to let an AI agent complete sign-up, login and 2FA on your own app
- How to test TOTP / authenticator 2FA in E2E tests
Humanless: disposable inboxes, dedicated US SMS numbers and TOTP for testing apps you own. Email and TOTP are free.
Get an API key