AssertInbox

Playwright sign-up with an emailed code: a runnable example

This is a small Playwright Test project you can download and run in a minute. It signs up on the AssertInbox practice app, a fake product that emails a six-digit code and a confirmation link, waits for that email through the AssertInbox API, types the code into the form and checks that the account is verified. Nothing is mocked: the mail is real and arrives at a real address. All you need is a key, because the practice app is hosted for you.

It uses @playwright/test major version 1 (the package.json asks for ^1.63.0) and Node 18 or newer. The project has two tests: one enters the emailed code and one opens the emailed link. The same shape works for your own application, where only the sign-up steps change.

Get a key

You need an AssertInbox key and its namespace. Get a key in one click: no email address or card is needed. The key is shown once, so keep it. Then export ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE (the namespace is shown with the key).

Download

Run these lines in an empty folder. They fetch every file below, each served as it is in the repository.

curl --create-dirs -fsSo package.json https://assertinbox.com/examples/playwright-signup-otp/package.json
curl --create-dirs -fsSo playwright.config.js https://assertinbox.com/examples/playwright-signup-otp/playwright.config.js
curl --create-dirs -fsSo tests/signup.spec.js https://assertinbox.com/examples/playwright-signup-otp/tests/signup.spec.js
curl --create-dirs -fsSo assertinbox.mjs https://assertinbox.com/examples/playwright-signup-otp/assertinbox.mjs
curl --create-dirs -fsSo .github/workflows/e2e.yml https://assertinbox.com/examples/playwright-signup-otp/ci/github-actions.yml
curl --create-dirs -fsSo README.md https://assertinbox.com/examples/playwright-signup-otp/README.md

Run it

npm install
npx playwright install chromium
export ASSERTINBOX_KEY=ai_...
export ASSERTINBOX_NAMESPACE=yournamespace
npx playwright test

By default the tests use the practice app at https://assertinbox.com/practice. Set PRACTICE_URL to point at another copy. Without a key and namespace the tests skip themselves and say how to get one.

The files

package.json

{
  "name": "assertinbox-playwright-signup-otp",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "playwright test"
  },
  "devDependencies": {
    "@playwright/test": "^1.63.0"
  }
}

playwright.config.js

import { defineConfig } from "@playwright/test";

// The practice app is a fake product that emails a code and a link to AssertInbox addresses.
const PRACTICE = (process.env.PRACTICE_URL || "https://assertinbox.com/practice").replace(/\/+$/, "");

export default defineConfig({
  testDir: "tests",
  fullyParallel: true,
  retries: process.env.CI ? 1 : 0,
  timeout: 60_000,
  reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : "list",
  use: {
    baseURL: PRACTICE + "/",
    trace: "retain-on-failure",
  },
});

tests/signup.spec.js

import { test, expect } from "@playwright/test";
import { AssertInbox } from "../assertinbox.mjs";

const key = process.env.ASSERTINBOX_KEY;
const namespace = process.env.ASSERTINBOX_NAMESPACE;

test.skip(!key || !namespace, "Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE. Create a key at https://assertinbox.com/start");

// One address per test: the tag is new every time, so parallel tests and retries never read each other's mail.
let inbox, tag, email;

test.beforeEach(() => {
  inbox = new AssertInbox({ key, namespace, baseUrl: process.env.ASSERTINBOX_URL || undefined, domain: process.env.ASSERTINBOX_DOMAIN || undefined });
  tag = inbox.uniqueTag("pw");
  email = inbox.address(tag);
});

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

async function signUp(page) {
  await page.goto("signup");
  await page.getByLabel("Email address").fill(email);
  await page.getByRole("button", { name: "Create account" }).click();
  await expect(page).toHaveURL(/\/practice\/verify/);
}

test("sign up and verify with the emailed code", async ({ page }) => {
  await signUp(page);
  const code = await inbox.waitForOtp(tag, { timeout: 25, retries: 2 });
  await page.getByLabel("Verification code").fill(code);
  await page.getByRole("button", { name: "Verify", exact: true }).click();
  await expect(page.getByRole("status")).toContainText("Your email is verified");
});

test("sign up and confirm with the emailed link", async ({ page }) => {
  await signUp(page);
  const link = await inbox.waitForLink(tag, { timeout: 25, retries: 2 });
  await page.goto(link);
  await expect(page).toHaveURL(/\/practice\/welcome/);
  await expect(page.getByRole("status")).toContainText("Your email is confirmed");
});

assertinbox.mjs

The AssertInbox client, identical to /sdk/assertinbox.mjs.

// AssertInbox client. MIT License. Copyright (c) AssertInbox. Zero dependencies; Node 18+ and browsers.
export class AssertInboxError extends Error {
  constructor(code, message, status) {
    super(message || code);
    this.name = "AssertInboxError";
    this.code = code;
    this.status = status;
  }
}

export class AssertInbox {
  constructor({ key, namespace, baseUrl = "https://assertinbox.com", domain, fetch: fetchFn } = {}) {
    if (!key) throw new Error("key is required");
    this.key = key;
    this.namespace = namespace;
    this.baseUrl = baseUrl.replace(/\/+$/, "");
    this.domain = domain || new URL(this.baseUrl).hostname.replace(/^www\./, "");
    this.fetch = fetchFn || ((...a) => globalThis.fetch(...a));
  }

  address(tag) {
    if (!this.namespace) throw new Error("namespace is required to build an address");
    return this.namespace + "." + String(tag).toLowerCase() + "@" + this.domain;
  }

  uniqueTag(prefix = "t") {
    return (prefix + "-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8)).toLowerCase();
  }

  async #request(path, params = {}, method = "GET") {
    const q = new URLSearchParams();
    for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== "") q.set(k, String(v));
    const qs = q.toString();
    const res = await this.fetch(this.baseUrl + path + (qs ? "?" + qs : ""), { method, headers: { Authorization: "Bearer " + this.key } });
    const body = await res.json().catch(() => ({}));
    if (!res.ok) throw new AssertInboxError(body.error || "http_" + res.status, body.message, res.status);
    return body;
  }

  // Waits for the newest matching message. A 408 timeout is retried up to `retries` more times.
  async wait({ tag, timeout = 20, from, subject, after, since, retries = 0 } = {}) {
    for (let attempt = 0; ; attempt++) {
      try {
        return await this.#request("/v1/wait", { tag, timeout, from, subject, after, since });
      } catch (e) {
        if (e.code !== "timeout" || attempt >= retries) throw e;
      }
    }
  }

  // Like wait(), but returns just the code. Throws, naming the subject, when the message has none.
  async waitForOtp(tag, opts = {}) {
    const message = await this.wait({ ...opts, tag });
    if (!message.otp) throw new Error('No code found in the email with subject "' + message.subject + '"');
    return message.otp;
  }

  // Like wait(), but returns just the magic link. Throws, naming the subject, when the message has none.
  async waitForLink(tag, opts = {}) {
    const message = await this.wait({ ...opts, tag });
    if (!message.magic_link) throw new Error('No link found in the email with subject "' + message.subject + '"');
    return message.magic_link;
  }

  async list({ tag, since, from, subject, after } = {}) {
    return (await this.#request("/v1/messages", { tag, since, from, subject, after })).messages;
  }

  async delete(tag) {
    return this.#request("/v1/messages", { tag }, "DELETE");
  }

  me() {
    return this.#request("/v1/me");
  }
}

const USAGE = `Usage: node assertinbox.mjs <command> [options]
  address <tag>                       print the address for a tag
  wait <tag> [--subject s] [--from f] [--after id] [--timeout n]   print the newest matching message as JSON
  otp <tag> [same options]            print only the code
  link <tag> [same options]           print only the magic link
  delete <tag>                        delete the messages of a tag
Environment: ASSERTINBOX_KEY, ASSERTINBOX_NAMESPACE; optional ASSERTINBOX_URL, ASSERTINBOX_DOMAIN.
Exit codes: 0 success, 1 timeout, no value or API error, 2 usage error.`;

// Command line behind `node assertinbox.mjs <command>`. Returns the exit code. The key is never printed.
export async function cli(argv, env = {}, out = (line) => console.log(line), err = (line) => console.error(line), fetchFn) {
  const usage = (why) => { err((why ? why + "\n" : "") + USAGE); return 2; };
  const [command, ...rest] = argv;
  if (!["address", "wait", "otp", "link", "delete"].includes(command)) return usage(command ? "Unknown command: " + command : "");
  const positional = [];
  const opts = {};
  for (let i = 0; i < rest.length; i++) {
    const m = /^--(subject|from|after|timeout)(?:=(.*))?$/.exec(rest[i]);
    if (!m) {
      if (rest[i].startsWith("--")) return usage("Unknown option: " + rest[i]);
      positional.push(rest[i]);
      continue;
    }
    const value = m[2] ?? rest[++i];
    if (value === undefined) return usage("Missing value for --" + m[1]);
    opts[m[1]] = value;
  }
  if (positional.length !== 1) return usage("Expected one tag");
  if (opts.timeout !== undefined && !(Number(opts.timeout) >= 0)) return usage("--timeout must be a number of seconds");
  if (command === "delete" && Object.keys(opts).length) return usage("delete takes no options");
  if (!env.ASSERTINBOX_KEY || !env.ASSERTINBOX_NAMESPACE) return usage("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE.");
  const client = new AssertInbox({ key: env.ASSERTINBOX_KEY, namespace: env.ASSERTINBOX_NAMESPACE, baseUrl: env.ASSERTINBOX_URL || undefined, domain: env.ASSERTINBOX_DOMAIN || undefined, fetch: fetchFn });
  const [tag] = positional;
  const filters = { subject: opts.subject, from: opts.from, after: opts.after, retries: 2, ...(opts.timeout !== undefined ? { timeout: Number(opts.timeout) } : {}) };
  try {
    if (command === "address") out(client.address(tag));
    else if (command === "delete") { await client.delete(tag); out("ok"); }
    else if (command === "otp") out(await client.waitForOtp(tag, filters));
    else if (command === "link") out(await client.waitForLink(tag, filters));
    else out(JSON.stringify(await client.wait({ ...filters, tag })));
    return 0;
  } catch (e) {
    err(e instanceof AssertInboxError ? e.code + ": " + e.message : String(e.message || e));
    return 1;
  }
}

// Run as a script: node assertinbox.mjs <command>. Importing the module never reaches the dynamic imports below.
if (globalThis.process?.argv?.[1]) {
  const { pathToFileURL } = await import("node:url");
  const { resolve } = await import("node:path");
  if (import.meta.url === pathToFileURL(resolve(process.argv[1])).href) process.exitCode = await cli(process.argv.slice(2), process.env);
}

.github/workflows/e2e.yml

name: e2e
on:
  push:
  pull_request:
jobs:
  playwright:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm install
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test
        env:
          ASSERTINBOX_KEY: ${{ secrets.ASSERTINBOX_KEY }}
          ASSERTINBOX_NAMESPACE: ${{ vars.ASSERTINBOX_NAMESPACE }}
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report/

README.md

# Playwright sign-up with an emailed code

A runnable Playwright Test project that signs up on the AssertInbox practice app, reads the emailed code (and, in a second test, the emailed link) through the AssertInbox API, and checks the result. It needs a key and nothing else: no app of your own.

Playwright Test major version: 1 (`@playwright/test` ^1.63.0). Node 18 or newer.

## Run it

```sh
npm install
npx playwright install chromium
export ASSERTINBOX_KEY=ai_...            # from https://assertinbox.com/start
export ASSERTINBOX_NAMESPACE=yournamespace
npx playwright test
```

`PRACTICE_URL` defaults to `https://assertinbox.com/practice`. Each test builds a fresh address, `<namespace>.pw-<random>@assertinbox.com`, and deletes its messages afterwards.

## Files

- `tests/signup.spec.js`: the two tests.
- `playwright.config.js`: base URL, parallel workers, one retry in CI.
- `assertinbox.mjs`: the AssertInbox client (a copy of https://assertinbox.com/sdk/assertinbox.mjs).
- `ci/github-actions.yml`: a GitHub Actions workflow, saved as `.github/workflows/e2e.yml`. Add `ASSERTINBOX_KEY` as a repository secret and `ASSERTINBOX_NAMESPACE` as a repository variable.

The practice app only sends to AssertInbox addresses. To test your own app, change `signUp()` to fill your form and keep the `waitForOtp` part.

How it works

Each test starts with inbox.uniqueTag(), so its address is new, for example yournamespace.pw-m2x8k1-q7zt3a@assertinbox.com. Parallel workers and retries therefore never read each other's mail, and a test deletes its own messages when it ends.

The test submits the sign-up form first and only then waits. waitForOtp long-polls the API for the newest message to that address and returns the extracted code; retries: 2 repeats the wait if the first poll times out. The link test uses waitForLink the same way, then opens the link in the same browser page. The practice app's rules are fixed: the code works once for 15 minutes, the link works once for 24 hours, and only AssertInbox addresses are accepted, so the example stays safe to run from CI.

To adapt it, replace the signUp() steps with your own form and keep the wait and the assertion. The workflow in ci/github-actions.yml keeps the key in a repository secret and the namespace in a repository variable, installs Chromium and runs the suite.

Related guides

Free beta, run by AI agents

This example was written by AI agents, and it ran for real: the two tests passed in Chromium with Playwright 1.63 against a local copy of the service on 6 December 2026. The GitHub Actions workflow has not been run in CI; it follows the usual Playwright setup.