AssertInbox

Test an Auth.js (NextAuth) magic-link sign-in with Playwright

Email sign-in with Auth.js (formerly NextAuth.js) sends a link, and the user is signed in when the link is opened. This guide tests that flow end to end in Playwright Test (plain JavaScript) against a Next.js app that uses the Auth.js Email (magic link) provider. The test enters a unique address, waits for the sign-in email with the subject and after filters, opens the magic_link and asserts that a session exists for that address. It also checks that the link points at the host you are testing, which is the most common mistake on preview deployments.

What the test needs from your app

The Email provider needs a database adapter, because it stores a verification token, and it needs a real mail transport. In Auth.js v4 the provider is called EmailProvider and the URL setting is NEXTAUTH_URL. In Auth.js v5 the provider is Nodemailer and the setting is AUTH_URL. The test below does not depend on the version: it uses the sign-in page, the emailed link and the /api/auth/session endpoint, which both versions serve by default. Check the exact option names in the Auth.js documentation for the version you run.

The app under test must deliver mail for real, through the SMTP server in its configuration, to the address the test enters. Point the test environment's mail settings at a transactional mail service you control; the address itself is an AssertInbox address.

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, links and magic_link. Messages are deleted after 24 hours. Auth.js sends a message whose subject is typically "Sign in to" followed by your host; the test matches the word sign in as a case-insensitive substring. If your app uses a custom sendVerificationRequest, change the filter to a word from your own subject.

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 CI secrets.

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

Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is 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 listed in the limits page.

The helper

Save this as tests/inbox.js. It needs Node 18 or newer for the built-in fetch. waitForEmail accepts the filters and retries on a 408 timeout, and latestId returns the id of the newest message for a tag, or undefined when there is none.

const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;

function headers() {
  return { Authorization: "Bearer " + KEY };
}

function newInbox(prefix) {
  const random = Math.random().toString(36).slice(2, 8);
  const tag = (prefix + "-" + Date.now() + "-" + random).toLowerCase();
  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: headers() });
    if (res.status === 200) return res.json();
    if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
  }
  throw new Error("No matching email arrived for tag " + tag);
}

async function latestId(tag) {
  const res = await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { headers: headers() });
  if (!res.ok) throw new Error("AssertInbox returned HTTP " + res.status);
  const body = await res.json();
  return body.messages.length ? body.messages[0].id : undefined;
}

async function deleteEmails(tag) {
  await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: headers() });
}

module.exports = { newInbox, waitForEmail, latestId, deleteEmails };

The test

Save this as tests/nextauth-magic-link.spec.js. Set APP_URL to the base URL of the app under test, for example the preview URL of a pull request. The labels and button names are those of the default Auth.js sign-in page; replace them if you use a custom page.

const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox");

const APP = process.env.APP_URL || "http://localhost:3000";

test.describe("Auth.js magic-link sign-in", () => {
  test.setTimeout(120000);
  let inbox;

  test.beforeEach(() => {
    inbox = newInbox("nextauth");
  });

  test.afterEach(async () => {
    await deleteEmails(inbox.tag);
  });

  async function requestLink(page) {
    const before = await latestId(inbox.tag);
    await page.goto(APP + "/api/auth/signin");
    await page.getByLabel("Email").fill(inbox.email);
    await page.getByRole("button", { name: /sign in with email/i }).click();
    return waitForEmail(inbox.tag, { subject: "sign in", ...(before ? { after: before } : {}) });
  }

  test("the emailed link signs the user in", async ({ page }) => {
    const mail = await requestLink(page);

    expect(mail.magic_link).toBeTruthy();
    expect(new URL(mail.magic_link).host).toBe(new URL(APP).host);

    await page.goto(mail.magic_link);
    const session = await page.request.get(APP + "/api/auth/session");
    expect(session.ok()).toBeTruthy();
    const body = await session.json();
    expect(body.user.email).toBe(inbox.email);
  });

  test("a second request sends a new link and the new link works", async ({ page }) => {
    const first = await requestLink(page);
    await page.goto(APP + "/api/auth/signin");
    await page.getByLabel("Email").fill(inbox.email);
    await page.getByRole("button", { name: /sign in with email/i }).click();
    const second = await waitForEmail(inbox.tag, { subject: "sign in", after: first.id });

    expect(second.id).not.toBe(first.id);
    await page.goto(second.magic_link);
    const body = await (await page.request.get(APP + "/api/auth/session")).json();
    expect(body.user.email).toBe(inbox.email);
  });
});

Run it with APP_URL=https://your-preview.example.com npx playwright test tests/nextauth-magic-link.spec.js. After the link is opened, Auth.js sets its session cookie on the page's browser context, so the page.request call that follows is signed in as well.

The link host must match your app's URL setting

Auth.js builds the link from its URL setting. If a preview deployment still carries the production value, or a value copied from local development, the email contains a link to another environment. The test then either fails the host assertion, which is what you want, or signs in on the wrong site and reports a green result that proves nothing. That is why the host assertion comes before page.goto. On a platform that gives each pull request its own URL, set the URL variable per deployment, or follow the Auth.js documentation on trusting the request host for your version.

Running against a preview deployment

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: Playwright email verification and password reset tests. 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.