Skip to main content

Playwright Login OTP: One Real SMS per Run, Then Reuse the Session

A Playwright setup project rents a number, reads the SMS code over an API, logs in once, and saves storageState so other tests skip the OTP.

Updated 11 min readMarkdown

Disclosure: I work with HeroSMS, the virtual number provider used in the examples. I wrote this post with AI tools, ran the code with Playwright 1.65 against a local mock of the app and the HeroSMS API (not the live service), and checked the endpoints against the HeroSMS API reference.

If your app logs users in with a code sent by SMS, every Playwright test that starts at the login page waits for a text message. Twenty tests mean twenty text messages: slow, costly, and a quick way to hit your own OTP rate limits. Playwright login OTP tests don't have to work like that. Log in once in a setup project with a real SMS, save the browser state with storageState, and start every other test already logged in. Below are the TypeScript setup test, a client for a phone-number API, and a nightly GitHub Actions job.

How the Playwright login OTP setup works

  1. Playwright runs the setup project before the tests that depend on it.
  2. The setup test opens your login form, rents a phone number, submits it, and polls the provider's API for the SMS with expect.poll.
  3. The test enters the code, waits for the logged-in page, and saves cookies and local storage to playwright/.auth/user.json.
  4. Every test in the chromium project starts from that file. No more texts until the next run.

If the setup test fails, the run summary counts the dependent tests as "did not run": one clear failure instead of twenty timeouts.

Does this fit your login?

  • The phone number is the login. The user types a number, gets a code, and is logged in, or signed up on the first code. Many phone-first apps and Firebase phone auth work this way. Each run then creates a fresh test user, so clean those up in staging. With Firebase on the web, real numbers go through its reCAPTCHA verifier and need an authorized domain (not localhost). If reCAPTCHA challenges the test browser, stay on fictional numbers.
  • SMS is a second factor on an existing account. The code goes to the number on that account, and a rented number is yours only until the rental ends. Have the setup create a fresh test user with the rented number through your staging admin API or seed script.
  • Playwright 2FA with an authenticator app (TOTP). You don't need a phone at all. Keep the test user's TOTP secret in CI secrets and generate the code in the test with any RFC 6238 library.

For quick checks on every pull request, use your auth provider's test numbers, such as Firebase's fictional phone numbers with a fixed code. They never touch a carrier, which is why the scheduled real-SMS run still matters.

Config: a setup project and a saved state

// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  use: { baseURL: process.env.APP_URL || "http://localhost:3000" },
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/, retries: 0 }, // every attempt rents a number
    {
      name: "chromium",
      use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" },
      dependencies: ["setup"],
    },
  ],
});
  • The setup project picks up auth.setup.ts through testMatch. The chromium project keeps the default pattern, which matches .spec and .test files, so the setup file doesn't run twice.
  • Each attempt rents a new number, hence retries: 0. It overrides the config-level retries, but a --retries command-line flag overrides it in turn, so don't pass one.

Add playwright/.auth to .gitignore. Playwright's authentication guide warns that the state file can hold cookies that would let someone impersonate your test account. For the same reason, don't upload it as a CI artifact.

A HeroSMS client on Playwright's request context

The examples use HeroSMS, the provider I work with. Its REST API takes an Authorization: ApiKey <key> header. Each purchase is an activation: one number for one service in one country. The service code ot is listed as "Any other" in the catalog. The client below uses Playwright's own APIRequestContext, so you don't need another HTTP library.

// tests/herosms.ts: rent a number, read its SMS, release it
import { request, type APIRequestContext } from "@playwright/test";

const API = "https://hero-sms.com/api/v1";

type Reply = { ok: boolean; status: number; json: any; text: string };

export class HeroSms {
  private constructor(private readonly ctx: APIRequestContext) {}

  static async create(): Promise<HeroSms> {
    const key = process.env.HEROSMS_API_KEY;
    if (!key) throw new Error("HEROSMS_API_KEY is not set");
    const ctx = await request.newContext({
      extraHTTPHeaders: { Authorization: `ApiKey ${key}` },
      timeout: 15_000,
    });
    return new HeroSms(ctx);
  }

  private async call(method: string, path: string, data?: object): Promise<Reply> {
    const res = await this.ctx.fetch(API + path, { method, data });
    const text = await res.text();
    let json: any = null;
    try { json = JSON.parse(text); } catch {} // empty (204) or HTML reply
    return { ok: res.ok(), status: res.status(), json, text };
  }

  async rent(country: number, maxPrice?: number) {
    const r = await this.call("POST", "/activations", {
      service: "ot", // "Any other"
      country,
      amount: 1,
      verificationType: "sms",
      ...(maxPrice ? { maxPrice } : {}),
    });
    const a = r.json?.data?.[0];
    if (!r.ok || !a) {
      const why = r.json?.details ?? r.text.slice(0, 200);
      throw new Error(`HeroSMS rent failed: HTTP ${r.status} ${r.json?.title ?? ""} ${why}`);
    }
    return { id: a.id as number, phone: `+${a.phone}` }; // phone comes without "+"
  }

  /** The code from the latest SMS, or "" while nothing has arrived. */
  async lastCode(id: number): Promise<string> {
    const r = await this.call("GET", `/activations/${id}/otp/last`).catch(() => null); // network error: ask again
    const otp = r?.ok ? r.json?.data : null;
    return otp?.smsCode || otp?.smsText?.match(/\b\d{4,8}\b/)?.[0] || "";
  }

  async release(id: number, gotSms: boolean) {
    try {
      const r = gotSms
        ? await this.call("POST", `/activations/${id}/finish`) // no refund
        : await this.call("DELETE", `/activations/${id}`); // cancel and refund
      if (!r.ok) console.warn(`HeroSMS activation ${id} not closed: HTTP ${r.status} ${r.json?.title ?? ""}`);
    } catch (e) {
      console.warn(`HeroSMS activation ${id} not closed: ${(e as Error).message}`);
    }
  }

  async dispose() {
    await this.ctx.dispose();
  }
}

Easy to miss:

  • lastCode() returns an empty string while nothing has arrived and on any error, so the poll asks again. If the API's smsCode field is empty, the regex takes the first 4- to 8-digit number from smsText.
  • The HeroSMS API reference lists a 2-minute minimum before a number can be canceled (EARLY_CANCEL_DENIED). That's why release() only logs a failed cancel: the test's own error stays visible. HeroSMS says that if no code arrives, the charge goes back to your balance automatically when the activation window (up to 20 minutes) ends.

The setup test: one real SMS, then storageState

// tests/auth.setup.ts: one real SMS login per run, saved for every other test
import fs from "node:fs";
import { expect, test as setup } from "@playwright/test";
import { HeroSms } from "./herosms";

const authFile = "playwright/.auth/user.json";
const MAX_AGE_MS = 6 * 60 * 60 * 1000; // keep below your app's session lifetime

setup("log in with a real SMS code", async ({ page }) => {
  const age = fs.existsSync(authFile) ? Date.now() - fs.statSync(authFile).mtimeMs : Infinity;
  setup.skip(age < MAX_AGE_MS, "saved session is still fresh");
  setup.setTimeout(360_000);

  await page.goto("/login");
  await expect(page.getByLabel("Phone number")).toBeVisible(); // a bad page fails before renting
  const sms = await HeroSms.create();
  const num = await sms.rent(Number(process.env.HEROSMS_COUNTRY || "16"));
  let code = "";
  try {
    await page.getByLabel("Phone number").fill(num.phone);
    await page.getByRole("button", { name: "Send code" }).click();

    await expect
      .poll(async () => (code = await sms.lastCode(num.id)), {
        message: `no SMS for activation ${num.id} within 4 minutes`,
        intervals: [5_000],
        timeout: 240_000,
      })
      .not.toBe("");

    await page.getByLabel("Verification code").fill(code);
    await page.getByRole("button", { name: "Verify" }).click();
    await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible({ timeout: 15_000 });
    await page.context().storageState({ path: authFile });
  } finally {
    await sms.release(num.id, code !== "");
    await sms.dispose();
  }
});

What each part does:

  • setup.skip() reuses a saved state that's less than 6 hours old. That matters on your machine: rerun the suite ten times in an afternoon and you pay for one text, not ten. In CI the file doesn't exist yet, so every run logs in fresh. Keep MAX_AGE_MS below your app's session lifetime; Playwright's guide says to delete the stored state once it expires.
  • setup.setTimeout(360_000) raises the 30-second default timeout to 6 minutes, enough for the 4-minute poll plus the page steps.
  • expect.poll() calls the function until the matcher passes or the timeout runs out. intervals: [5_000] waits 5 seconds between API calls, and the message names the activation.
  • The test checks for the phone field before it rents a number, so an unreachable APP_URL or a broken staging page costs nothing.
  • The finally block always tries to finish or cancel the activation, even when a locator times out. A cancel that comes too early only logs a warning.
  • The test waits up to 15 seconds for a logged-in element before it saves the state, because some login flows set cookies across several redirects. Replace the labels and the "Dashboard" heading with your app's.
  • If your app keeps its tokens in IndexedDB, as Firebase Authentication does, save with storageState({ path: authFile, indexedDB: true }). IndexedDB isn't in the snapshot by default.

Tests that start logged in

// tests/dashboard.spec.ts: starts logged in, sends no SMS
import { expect, test } from "@playwright/test";

test("dashboard opens without a new login", async ({ page }) => {
  await page.goto("/dashboard");
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

Run npx playwright test: setup goes first, then everything else runs logged in. To check the logged-out view in one file, reset the state there with test.use({ storageState: { cookies: [], origins: [] } }).

For tests that change shared server-side state, Playwright's guide recommends one account per parallel worker; here, that means one rented number per worker.

Run it nightly in GitHub Actions

name: e2e-sms-login
on:
  schedule:
    - cron: "15 4 * * *"
  workflow_dispatch:
concurrency: e2e-sms-login
jobs:
  e2e:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 24
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test
        env:
          APP_URL: ${{ vars.STAGING_URL }}
          HEROSMS_API_KEY: ${{ secrets.HEROSMS_API_KEY }}
          HEROSMS_COUNTRY: "16"

Save it as .github/workflows/e2e-sms-login.yml. Put HEROSMS_API_KEY in your repository secrets and the staging address in a repository variable named STAGING_URL. The job runs daily at about 04:15 UTC (GitHub can delay scheduled runs) or by hand from the Actions tab, and concurrency keeps two runs from overlapping. Each run buys one number, so schedule it nightly and before releases, not on every push.

Playwright login OTP errors and fixes

Symptom Cause and fix
no SMS for activation … within 4 minutes The app never sent the code (check its logs), the SMS arrived late or never reached the number, or the activation was closed. Rerun with a new number
Tests land on the login page The saved session expired or was revoked. Delete playwright/.auth/user.json; if it expired, also lower MAX_AGE_MS
Logged in during setup, logged out in tests Tokens in IndexedDB (add indexedDB: true) or in session storage, which storageState doesn't save (see Playwright's auth guide)
HeroSMS rent failed: HTTP 403 BAD_API_KEY The secret holds a wrong or revoked key; replace it
"not closed" warning after a quick failure The cancel came too early; HeroSMS says the activation is refunded when its window ends
UI mode never logs in UI mode doesn't run the setup project by default. Enable setup in the project filter, run it, then turn it off

If you add logging, never print the code. Playwright's HTML report and traces also record what fill() typed, so keep them private, like the state file.

Use rented numbers only on apps you own or are authorized to test, and don't tie them to accounts you'll need later: a number is yours only while its activation lasts.

For codes pushed by webhook instead of polled, see my Playwright OTP post on dev.to. For the same pattern in other stacks, see Cypress with a real phone number and Twilio Verify Test Numbers.

About the author

  • I work with HeroSMS, a virtual phone number service, and write practical guides on testing SMS/OTP flows: Python scripts, Playwright end-to-end tests, webhooks and CI pipelines. I focus on code you can actually run and on the parts of phone verification that tend to break.

No comments yet. Be the first to comment.