Guide: Testing Magic Link Login
To test magic link login, request the link for a fresh inbox, wait for the email with waitFor(), choose your sign-in URL from email.links and open it, then assert you are signed in.
How to Test a Magic Link
Every email you receive comes back with its links already extracted, so there is no HTML parsing. Filter them by host and path to find the sign-in link, open it once with a browser or an HTTP client, and check the session it creates. This works with any test runner.
TypeScript
magic-link.test.ts
import { ReceiverClient } from "@receiverdotemail/sdk";
const receiver = new ReceiverClient(); // reads RECEIVER_API_KEY
const APP = "https://your-app.com";
/** The first link to your app whose path starts with pathPrefix. */
function findLink(links: string[], pathPrefix: string): string | undefined {
return links.find((link) => {
const url = new URL(link);
return url.origin === APP && url.pathname.startsWith(pathPrefix);
});
}
it("logs in with a magic link", async () => {
// 1. A unique address for this test
const inbox = await receiver.inboxes.create({ prefix: "magic" });
// 2. Request the link
await fetch(`${APP}/api/auth/magic-link`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: inbox.address }),
});
// 3. Wait for the email (throws ReceiverTimeoutError if it never comes)
const email = await receiver.emails.waitFor({
recipient: inbox.address,
since: inbox.createdAt,
timeout: 60,
});
// 4. Pick the sign-in link
const magicLink = findLink(email.links, "/auth/verify");
expect(magicLink).toBeDefined();
// 5. Open it: expect a redirect that sets the session cookie
const res = await fetch(magicLink!, { redirect: "manual" });
expect([302, 303]).toContain(res.status);
expect(res.headers.get("set-cookie")).toContain("session=");
}, 90_000);Python
test_magic_link.py
from urllib.parse import urlparse
import httpx
import pytest
from receiverdotemail import ReceiverClient
APP = "https://your-app.com"
def find_link(links, path_prefix):
"""The first link to your app whose path starts with path_prefix."""
for link in links:
url = urlparse(link)
if f"{url.scheme}://{url.netloc}" == APP and url.path.startswith(path_prefix):
return link
return None
@pytest.mark.asyncio
async def test_magic_link_login():
async with ReceiverClient() as receiver: # reads RECEIVER_API_KEY
inbox = await receiver.inboxes.create(prefix="magic")
async with httpx.AsyncClient() as http:
await http.post(f"{APP}/api/auth/magic-link", json={"email": inbox.address})
email = await receiver.emails.wait_for(
recipient=inbox.address,
since=inbox.created_at,
timeout=60,
)
magic_link = find_link(email.links, "/auth/verify")
assert magic_link is not None, email.links
res = await http.get(magic_link) # no redirects followed
assert res.status_code in (302, 303)
assert "session" in res.cookiesOpening the Link in a Browser
If the session lives in the browser, open the link in the test's browser instead of an HTTP client, so the cookie is set where the rest of the test runs:
- Playwright:
await page.goto(magicLink). See Testing Emails in Playwright. - Cypress: return the link from a
cy.taskandcy.visit()it. See Testing Emails in Cypress.
Picking the Right Link
A sign-in email usually has several links: the magic link, a logo, help pages, unsubscribe and tracking URLs. Match on what makes yours unique:
- Host and path: compare the parsed URL's origin and path rather than searching for a substring anywhere in the URL.
- Click tracking: providers such as SendGrid, Mailgun or Resend can rewrite links into tracking redirects. Turn click tracking off for your test environment so the real URL is in the email.
- Subject filter: if one address receives several kinds of email, pass
subjecttowaitFor()(a case-insensitive substring) so only the sign-in email matches.
Expiry, Reuse and Resends
- Single use: open the link exactly once. Opening it a second time is a good negative test: assert it is rejected.
- Requesting a new link: wait with
sinceset to the first email'sreceivedAt. Only the newer email can match, so you can assert the old link stops working. - Codes and links together: if the email also shows a code,
waitForOtp()returns it; see Testing OTP / 2FA.
Next Steps
- Testing Password Resets: the same link pattern for resets
- CI/CD Integration: run it in your pipeline
- Concepts: how
sinceworks