Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a controlled authentication setup, save Playwright’s storageState, and load it into the tests that need it. This avoids interactive login on every test, but the saved file is a credential: cookies and headers in it may be enough to impersonate the account. Keep it out of version control, isolate it by worker when tests change shared data, and refresh it when it expires. For passkey (WebAuthn) coverage, use a virtual authenticator or the WebAuthn protocol rather than a physical key. Other factors—including TOTP, push, SMS and recovery challenges—remain application-specific and must be validated with an authorized test account.

What “handling 2FA” means in a Playwright test suite

Two-factor authentication is normally an interactive security step. A maintainable test suite does not repeatedly automate a production login or attempt to defeat a challenge. Instead, create a dedicated, authorized test account, complete its approved authentication flow in a controlled setup, save the resulting browser state, and reuse that state in tests.

  • Reusable state: cookies, local storage and other headers are loaded with storageState.
  • Isolation: use a separate account and state for each parallel worker when tests mutate server-side data.
  • WebAuthn: seed a virtual authenticator for passkey ceremonies; no hardware key is required for this automated path.
  • Other MFA: TOTP, push, SMS, recovery codes and identity-provider-specific screens need an application-specific, authorized design.

Save an authenticated state once

Create a setup project that signs in through the same supported UI your users use. Store the state in the test output directory so it is recreated for a run and is not accidentally committed.

Project files

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

export default defineConfig({
  testDir: './tests',
  projects: [
    {
      name: 'setup',
      testMatch: /.*.setup.ts/,
    },
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        storageState: 'test-results/.auth/user.json',
      },
      dependencies: ['setup'],
    },
  ],
});

Authenticate in the setup project

// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
import path from 'node:path';

const authFile = path.join('test-results', '.auth', 'user.json');

setup('authenticate', async ({ page }) => {
  await page.goto('https://example.test/login');
  await page.getByLabel('Email').fill(process.env.E2E_EMAIL!);
  await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();

  // Complete only the MFA method your test account is explicitly authorized to use.
  // For a test-only account, this might be an approved test mailbox, TOTP service,
  // or passkey ceremony supplied by your identity provider.
  await expect(page).toHaveURL(/dashboard/);
  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();

  await page.context().storageState({ path: authFile });
});

Do not hard-code credentials or one-time codes. Supply secrets through your CI secret store or environment, and make the setup fail if the expected post-login page is not reached. A state file that was produced before MFA completed is not an authenticated state.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Consume the state in a test

// tests/account.spec.ts
import { test, expect } from '@playwright/test';

test('shows the signed-in account', async ({ page }) => {
  await page.goto('https://example.test/account');
  await expect(page.getByRole('heading', { name: 'Account' })).toBeVisible();
});

Run the setup and dependent project with npx playwright test. If the application expires sessions during a run, delete the old state and run setup again rather than weakening the login policy.

Choose shared or per-worker accounts

Pattern Use it when Important control
One setup account and shared state Tests are read-only or can safely run concurrently against the same account. Ensure tests do not overwrite one another’s records, preferences or carts.
Separate account and state per worker Parallel tests change shared server-side data. Provision deterministic accounts and create one state file per worker.

Parallelism makes a single account unsafe when one test changes data another test is asserting. A worker-scoped fixture can select credentials by worker index, run the same controlled setup, and save user-<workerIndex>.json. Keep account provisioning outside the test run or make it idempotent.

Is Playwright storageState safe to commit?

No. Treat every state file as a password-equivalent secret. It can contain session cookies, bearer-like headers and local storage values that let whoever obtains it act as the account without entering a password or second factor.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  • Add the authentication directory to .gitignore; do not commit it to a public or private repository.
  • Restrict filesystem and CI-artifact access to the test job that needs it.
  • Use short-lived test accounts with minimal permissions and non-production data.
  • Write run-only state under the output directory, which can be cleaned before a run.
  • Delete and regenerate state after expiry, account rotation or suspected exposure.
  • Redact state paths and contents from logs and uploaded artifacts.

Revoking the test account’s sessions is the recovery step if a state file leaks. Rotating the password alone may not invalidate every existing cookie, depending on the identity provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can Playwright automate passkey authentication?

Yes, for WebAuthn ceremonies. Playwright’s virtual authenticator can create credentials and answer registration and assertion requests in a browser context. The documented Credentials API was added in Playwright v1.61, so pin the runner version and verify the API available in your project before adopting it. This feature is specifically WebAuthn; it is not a universal automation API for every MFA factor.

What the virtual authenticator represents

  • It can be configured for resident keys, user verification and the transport your test needs.
  • Known credentials can be seeded so a test begins with a registered passkey.
  • Serialized virtual credential data includes private keys and is therefore highly sensitive.
  • Restoring state that contains virtual credentials installs that authenticator in the context; real authenticators will not work in that context.

Keep virtual-authenticator state in the smallest possible set of tests. Do not share it with ordinary browser tests or publish it as a CI artifact.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Chromium WebAuthn example through CDP

If your project targets Chromium, the DevTools WebAuthn domain provides a stable way to exercise a virtual authenticator. This example is intentionally limited to a test account and a test origin:

import { chromium } from 'playwright';

const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
const cdp = await context.newCDPSession(page);

await cdp.send('WebAuthn.enable');
const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', {
  options: {
    protocol: 'ctap2',
    transport: 'internal',
    hasResidentKey: true,
    hasUserVerification: true,
    automaticPresenceSimulation: true,
  },
});

await page.goto('https://example.test/passkey-enrollment');
// Complete the site’s authorized registration flow here. The browser will
// answer WebAuthn create/get requests with the virtual authenticator.
await page.getByRole('button', { name: 'Register passkey' }).click();

// Remove the authenticator when this isolated test is complete.
await cdp.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId });
await browser.close();

For the newer Playwright Credentials API, use the exact method names and options documented for the version pinned in your repository. A version mismatch commonly appears as a missing-method error; upgrading or pinning the runner is safer than silently falling back to a real key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What about TOTP, push, SMS and recovery codes?

There is no single Playwright switch that safely automates all MFA systems. Build a test-only integration appropriate to the provider: for example, inject a known TOTP secret into a controlled test account, consume a message from an authorized test mailbox, or use the provider’s documented test mode. Never intercept or bypass a real user’s second factor.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
  • TOTP: keep the seed in CI secrets, generate codes only for the test account, and account for clock skew and single-use windows.
  • Push approval: use a provider-supported sandbox or deterministic approval endpoint; do not automate an employee’s phone.
  • SMS: use a test number or provider sandbox, not a personal number or production traffic.
  • Recovery: reserve recovery codes for explicit recovery tests and rotate them after use.
  • Identity-provider challenges: coordinate with the IdP owner; challenge screens and policies vary by tenant.

Physical security keys versus virtual WebAuthn

A real FIDO2 key is appropriate when a human administrator must enroll hardware or when you are manually checking hardware-backed behavior. It is not required for automated Playwright WebAuthn ceremonies. Use the virtual authenticator for repeatable CI coverage and reserve physical-key checks for a separate, controlled manual or hardware test.

Troubleshooting authentication failures

Symptom Likely cause Fix
Tests redirect to login State was saved before MFA completed, expired, or was written to a different path. Assert the post-login URL, inspect the resolved path, delete the file and rerun setup.
“Unauthorized” after parallel tests start One account’s data or session is being changed concurrently. Use separate accounts and state files per worker.
State works locally but not in CI Different base URL, domain, clock, environment variables or secret values. Log non-secret configuration, use the same origin, synchronize time and verify CI secrets.
WebAuthn registration says no authenticator Virtual authenticator was not enabled, lacks user verification, or the browser is unsupported. Enable it before navigation, set required options, and run the test in the browser engine supported by your implementation.
Real key stops working The context restored a virtual authenticator. Use a fresh context without virtual credentials for hardware tests.
Random MFA timeouts One-time code window, push latency or network timing. Use a provider sandbox, wait on a deterministic signal, and avoid arbitrary sleeps where an event or selector is available.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and cost controls

  • Authenticate once per setup or worker rather than once per test.
  • Keep setup assertions narrow: confirm the authenticated origin and one protected control, then let feature tests cover behavior.
  • Use independent accounts only where mutation requires them; account provisioning and cleanup can otherwise dominate run time.
  • Prefer deterministic provider sandboxes over live SMS or push networks.
  • Run a scheduled job that detects expired state and regenerates it; never hide expiry by disabling MFA.
  • Record browser and Playwright versions with the run so a WebAuthn API change is diagnosable.

Or skip the browser setup

If you need images of authenticated or public pages for test evidence, documentation or monitoring, ScreenshotNeo provides a one-call screenshot API. It is separate from MFA authentication: it does not replace your authorized login flow or bypass a challenge.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. The service removes cookie-consent banners, newsletter popups and chat widgets before capture; bot checks, blank pages and failed loads are not billed, and each response identifies the page verdict and billing status. Its MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

How do I handle 2FA in Playwright?

Authenticate an authorized test account in a setup project, complete its approved MFA path, save storageState, and reuse that state. The exact second-factor integration depends on your identity provider.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Can a virtual authenticator test every MFA method?

No. It covers WebAuthn passkey create/get ceremonies. TOTP, push, SMS, recovery and provider-specific challenges require separate, application-specific test arrangements.

When should I buy a FIDO2 key?

Use one for human enrollment or manual hardware-backed checks. Automated Playwright WebAuthn coverage can use a virtual authenticator instead.

Frequently Asked Questions

How do I handle 2FA in Playwright?

Authenticate an authorized test account in a setup project, complete its approved MFA path, save storageState, and reuse that state. The exact second-factor integration depends on your identity provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can a virtual authenticator test every MFA method?

No. It covers WebAuthn passkey create/get ceremonies. TOTP, push, SMS, recovery and provider-specific challenges require separate, application-specific test arrangements.

When should I buy a FIDO2 key?

Use one for human enrollment or manual hardware-backed checks. Automated Playwright WebAuthn coverage can use a virtual authenticator instead.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.