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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Authenticate once in a Playwright setup project, save the browser context with storageState, and configure dependent projects to load that file. Your page object model (POM) should wrap the already-authenticated page; it should not own the login lifecycle. Use one shared account only when tests can run concurrently without changing the same server-side data. If tests mutate shared data, create separate accounts and state files per worker.

The boundary: authentication setup versus a POM

Playwright defines a page object as an application-focused layer that centralizes selectors and reusable operations. The POM gives tests a higher-level API; the browser context supplies cookies, local storage and other browser state. Keeping those responsibilities separate makes authentication replaceable and prevents every page object from implementing its own login sequence.

The arrangement is:

  1. A setup project logs in (through the UI or an API) and writes a state file.
  2. Test projects depend on setup and set use.storageState to that file.
  3. Fixtures construct POMs from the authenticated page fixture.

See Playwright’s authentication guide, page object model guide and TestOptions reference.

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.

Authenticate once in a setup project

Create the setup test

Create tests/auth.setup.ts. Adapt routes, credentials, selectors and the signed-in condition to your application; the example values below are not universal.

#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
import { test as setup, expect } from '@playwright/test';
import path from 'node:path';

const authFile = path.resolve('playwright/.auth/user.json');

setup('authenticate', async ({ page }) => {
  await page.goto('https://your-app.example/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();

  // Prefer a durable post-login signal.
  await expect(page).toHaveURL(/dashboard/);
  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();

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

Waiting for a final URL or authenticated UI element is safer than saving immediately after a click. If the application completes login asynchronously, wait for the element or response that proves the session is usable.

Configure project dependencies

import { defineConfig, devices } from '@playwright/test';
import path from 'node:path';

const authFile = path.resolve('playwright/.auth/user.json');

export default defineConfig({
  testDir: './tests',
  projects: [
    {
      name: 'setup',
      testMatch: /.*\.setup\.ts/,
    },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: authFile },
      dependencies: ['setup'],
    },
  ],
});

The dependency causes the setup project to run before the Chromium project. Add equivalent projects for Firefox or WebKit when their authentication state is valid for those browsers.

Build POMs on the authenticated page

Wrap the standard page fixture

import { expect, type Locator, type Page } from '@playwright/test';

export class DashboardPage {
  readonly heading: Locator;
  readonly projectsLink: Locator;

  constructor(private readonly page: Page) {
    this.heading = page.getByRole('heading', { name: 'Dashboard' });
    this.projectsLink = page.getByRole('link', { name: 'Projects' });
  }

  async expectLoaded() {
    await expect(this.heading).toBeVisible();
  }

  async openProjects() {
    await this.projectsLink.click();
  }
}

Because the project configuration initializes the context from user.json, every test using the normal page fixture starts authenticated.

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

Expose the POM as a fixture

import { test as base } from '@playwright/test';
import { DashboardPage } from './pages/dashboard-page';

type Fixtures = { dashboard: DashboardPage };

export const test = base.extend<Fixtures>({
  dashboard: async ({ page }, use) => {
    await use(new DashboardPage(page));
  },
});

export { expect } from '@playwright/test';
import { test } from './fixtures';

test('opens projects for an authenticated user', async ({ dashboard }) => {
  await dashboard.expectLoaded();
  await dashboard.openProjects();
});

Alternatively, instantiate new DashboardPage(page) inside an individual test. Fixtures are useful when many tests need the same POM and keep construction consistent.

Rank #2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

One account or one account per worker?

Use one shared state when isolation is unnecessary

Playwright’s basic approach is suitable when tests can run at the same time without affecting one another and authentication is not browser-specific. A shared account minimizes provisioning and setup code. It is a poor fit for tests that rename the same record, change permissions, consume a one-time token or otherwise alter data another test reads.

Use worker-scoped accounts for mutating tests

Provision a unique account for each parallel worker and generate that worker’s state once. The worker index is available through test.info().parallelIndex. A worker fixture can write to a distinct file:

import { test as base } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';

export const test = base.extend<{}, { workerStorageState: string }>({
  workerStorageState: [async ({}, use, workerInfo) => {
    const file = path.resolve(`test-results/.auth/worker-${workerInfo.parallelIndex}.json`);
    fs.mkdirSync(path.dirname(file), { recursive: true });

    // Replace this call with your account-provisioning and login routine.
    await authenticateUniqueWorker(workerInfo.parallelIndex, file);
    await use(file);
  }, { scope: 'worker' }],
});

async function authenticateUniqueWorker(index: number, file: string) {
  // Create or select account index, then save context.storageState({ path: file }).
}

Configure the worker’s context to use that file in the fixture or project design. Separate accounts cost more to manage, but they prevent parallel workers and team members from colliding. Do not share a state file when the login itself is browser-specific.

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

Use separate roles in one test

For an administrator and a regular user in the same scenario, create separate contexts from separate state files. A POM wraps a page, while the context establishes the role.

Rank #3
Kosbees 500 GB External Hard Drives,Portable Hard Drive for Windows,Ultra Slim External HDD Store Compatible with PC, MAC,Laptop,PS4, Xbox one, Xbox 360;Plug and Play Ready
  • 【Plug-and-Play Expandability】 With no software to install, just plug it in and the drive is ready to use in Windows(For Mac,first format the drive and select the ExFat format.
  • 【Fast Data Transfers 】The external hard drives with the USB 3.0 cable to provide super fast transfer speed. The theoretical read speed is as high as 110MB/s-133MB/s, and the write speed is as high as 103MB/s.
  • 【High capacity in a small enclosure 】The small, lightweight design offers up to 500GB capacity, offering ample space for storing large files, multimedia content, and backups with ease. Weighing only 0.35 Lbs, it's easy to carry "
  • 【Wide Compatibility】Supports PS4 5/xbox one/Windows/Linux/Mac and other operating systems, ensuring seamless integration with game consoles,various laptops and desktops .
  • Important Notes for PS/Xbox Gaming Devices: You can play last-gen games (PS4 / Xbox One) directly from an external hard drive. However, to play current-gen games (PS5 / Xbox Series X|S), you must copy them to the console's internal SSD first. The external drive is great for keeping your library on hand, but it can't run the new games.
import { test as base } from '@playwright/test';
import { AdminPage } from './pages/admin-page';
import { UserPage } from './pages/user-page';

export const test = base.extend<{ admin: AdminPage; user: UserPage }>({
  admin: async ({ browser }, use) => {
    const context = await browser.newContext({
      storageState: 'playwright/.auth/admin.json',
    });
    const page = await context.newPage();
    await use(new AdminPage(page));
    await context.close();
  },
  user: async ({ browser }, use) => {
    const context = await browser.newContext({
      storageState: 'playwright/.auth/user.json',
    });
    const page = await context.newPage();
    await use(new UserPage(page));
    await context.close();
  },
});

UI login versus API login

If your application exposes a practical authentication endpoint, use Playwright’s APIRequestContext to authenticate and save its state. The API-testing guide documents that state is interchangeable between APIRequestContext and BrowserContext: https://playwright.dev/docs/api-testing.

import { request, test as setup } from '@playwright/test';

setup('authenticate through the API', async ({ storageState }) => {
  const api = await request.newContext({ baseURL: 'https://your-app.example' });
  const response = await api.post('/api/login', {
    data: { email: process.env.E2E_EMAIL, password: process.env.E2E_PASSWORD },
  });
  if (!response.ok()) throw new Error(`Login failed: ${response.status()}`);
  await api.storageState({ path: 'playwright/.auth/user.json' });
  await api.dispose();
});

API login can avoid brittle UI steps, but only use it when the endpoint and security model are intended for this purpose. UI login remains appropriate when browser behavior itself is what you need to exercise.

Protect and refresh state files

Playwright warns: “The browser state file may contain sensitive cookies and headers that could be used to impersonate you or your test account.” Store files under playwright/.auth, add that directory to .gitignore, and never commit them, including to a private repository.

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

If persistence between runs is unnecessary, write state beneath the test project’s output directory so Playwright can clean it before a run. When a session expires, delete the file and rerun setup. In UI mode, setup projects do not run automatically by default; run the setup test manually when the existing state expires.

Rank #4
YOTUO 1TB External Hard Drive, Portable Storage Expansion HDD, USB 3.0 & USB-C for PC, Mac, Desktop, Laptop, Smartphone, PS4, Xbox One, Xbox 360, Office & Game, Black
  • 【Versatile Storage Expansion – For Gaming, Work & Everyday Use】 Running out of space on your PS5 or Xbox Series X/S? This external hard drive lets you store and play PS4 / Xbox One games directly, instantly freeing up your console’s internal storage for next‑gen titles. At the same time, it handles work file backups, media libraries, and cross‑device data transfers with ease. One drive, all your needs. *(Note: PS5 / Xbox Series X|S games cannot be run or stored directly from the external hard drive. However, by offloading your PS4 / Xbox One games, you can free up valuable space for newer titles.)*
  • 【Patented Silicone Sleeve – Data Protection You Can Count On】 Worried about drops? We’ve got you covered. The patented built‑in silicone sleeve acts like a shock‑absorbing armor, cushioning your drive against bumps and falls. Whether it’s important work documents, precious family photos, or hard‑earned game saves, your data deserves this level of protection.
  • 【Plug & Play, Compatible with Computers & Consoles】 No complicated setup—just plug in and go. Works seamlessly with Windows, Mac, and Linux computers, as well as PS4, PS5, Xbox One, and Xbox Series X/S. Process files at the office, back up data at home, or enjoy gaming in your downtime—one drive handles all your devices, simply and hassle‑free.
  • 【USB 3.0 Ultra‑Fast Transfer – No More Waiting】 Tired of watching progress bars crawl? With USB 3.0 speeds up to 5Gbps, large files transfer in seconds. Whether you’re moving work documents, transferring hundreds of gigs of games, or backing up a year’s worth of photos, you get more done in less time.
  • 【Sleek, Lightweight, and Ready to Go】 Weighing just 0.16 kg—lighter than a can of soda—this compact drive features a stylish mirror‑and‑frosted finish. Toss it in your bag and go, whether you’re heading to the office, visiting a friend for a gaming session, or giving a presentation on the road.

What storageState includes—and what it does not

  • Standard state reuse covers cookies and local storage.
  • IndexedDB snapshot support was added in Playwright v1.51; enable the relevant storageState option and verify your installed version.
  • Virtual WebAuthn credential inclusion is supported through the credentials option from Playwright v1.61.
  • Session storage is not automatically persisted by the standard state file. It is domain-specific; capture it yourself and seed it with context.addInitScript, following the session-storage example in the authentication guide.

Check the BrowserContext API reference for the exact options supported by your installed version.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The test is redirected to login

Verify that the setup project ran, the state path is absolute or resolves from the expected working directory, and the setup test waited for a completed login. Open the state file only in a secure environment and check that the expected cookie or local-storage entry exists.

Workers change each other’s data

Replace the shared account with unique accounts and worker-scoped state. Also remove tests’ dependence on fixed record names; generate identifiers per worker where possible.

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

State works in Chromium but not another browser

Authentication may be browser-specific. Generate state separately for each browser project instead of reusing one file indiscriminately.

Best Value
Sale
Aiolo Innovation 500GB External Hard Drive Ultra Slim Portable HDD-USB 3.0 for PC, Mac, Laptop, PS4, Xbox one,Xbox 360 HD-A4
  • Ultra fast data transfers: the external hard drive works with USB 3.0 thickened copper cable to provide super fast transfer speeds. Theoretical read speed is as high as 110MB/s-133MB/s and write speed is as high as 103MB/s.
  • Ultra-thin and quiet: the motherboard adopts a noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • Compatibility: compatible with PS4/xbox one/Windows/Linux/Mac/Android,Stable and fast downloading on game console no difference from fast transmission when using on PC.
  • Plug and Play: no software to install, just plug it in and the drive is ready to use. The hard drive chip is wrapped with aluminum anti-interference layer to increase heat dissipation and protect data
  • Package Contents: 1* portable hard drive, 1 *USB 3.0 cable, 1*USB to type C adapter,1 *user manual, shell packaging, three-year manufacturer's warranty and free technical support services

IndexedDB or passkey authentication is missing

Confirm the Playwright version and explicitly enable the IndexedDB or virtual-credential option supported by that version. A cookie-only state file cannot recreate data stored elsewhere.

Login setup is slow or flaky

Use API authentication when the application provides a stable supported endpoint; otherwise wait on a deterministic URL or authenticated element rather than a fixed timeout. Keep setup separate from test assertions so failures identify the authentication boundary.

Performance, reliability and cost decisions

  • One setup login per run is faster than repeating UI login in every test.
  • Worker-scoped setup adds account provisioning and storage files, but removes data races that cause retries and nondeterministic failures.
  • A persistent file reduces repeated login work across runs but requires expiry handling and secret hygiene.
  • Output-directory state is safer for ephemeral credentials because it is cleaned with test artifacts.

Or skip the browser setup

If your goal is producing page images rather than exercising an authenticated Playwright suite, ScreenshotNeo provides a single screenshot API request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; bot checks, blank pages, failed loads, timeouts and cache hits are not billed, with the result identified by X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 options such as full-page capture, selectors, device presets, custom headers and cookies, JavaScript, waiting conditions, PDFs, signed links and bulk capture.

The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I instantiate a POM before authentication finishes?

No. Construct it after the page belongs to a context initialized with the required storage state; otherwise its actions run against an unauthenticated session.

Should state files be committed to a private repository?

No. They may contain impersonation-capable cookies and headers. Keep them git-ignored and regenerate them when they expire.

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

Does storageState persist sessionStorage automatically?

No. Session storage requires custom capture and an init script; standard state handling does not include it.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$129.99
Bestseller No. 2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80

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.