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

Use a Playwright setup project to log in once, save storageState, and load that state in tests whose UI actions live in Page Object Model (POM) classes. This approach keeps authentication out of individual tests, works with fixtures, and appears in the HTML report. Playwright’s documentation recommends project dependencies over the older globalSetup option when you need traces, fixtures, and test-runner visibility.

The recommended architecture

Separate the workflow into four parts:

  1. A setup test signs in and writes an authentication-state file.
  2. A dependent project loads that file through use.storageState.
  3. A custom fixture constructs the POM with the already-authenticated Page.
  4. Tests call POM methods instead of locating page elements directly.

The state file can contain cookies, local storage, IndexedDB, and (in versions that support them) passkey-related state. Session storage is not included and requires a separate restoration method.

Use the current Playwright documentation for authentication and global setup and teardown. Match examples to the Playwright version installed in your project; the BrowserContext reference marks virtual WebAuthn credentials as added in v1.61.

Project layout and configuration

A practical TypeScript layout is:

playwright.config.ts
playwright/
  auth.setup.ts
  pages/account-page.ts
  fixtures.ts
tests/
  account.spec.ts
playwright/.auth/

Create the authentication directory and ignore it in Git. Playwright explicitly recommends adding playwright/.auth to .gitignore, because state files can contain cookies and headers that impersonate an account.

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.
# .gitignore
playwright/.auth/

Configure a setup project and make browser projects depend on it:

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

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

The dependency causes the setup test to run before Chromium tests. It is visible in the HTML report and can use the normal browser fixture, traces, and other runner features.

Save state after the login is complete

Do not save immediately after clicking a login button. Wait for a URL, heading, or other condition that proves the server has established the session.

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

setup('authenticate user', 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();

  await expect(page).toHaveURL(//dashboard/);
  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();

  await page.context().storageState({
    path: 'playwright/.auth/user.json',
  });
});

Keep credentials in environment variables or your CI secret store. If your application redirects through an identity provider, wait for the final application URL and a stable authenticated element rather than relying on a fixed delay.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Put screen behavior in a POM

A page object wraps one Page and exposes the locators and operations belonging to that screen.

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

export class AccountPage {
  readonly heading: Locator;
  readonly nameInput: Locator;
  readonly saveButton: Locator;

  constructor(readonly page: Page) {
    this.heading = page.getByRole('heading', { name: 'Account' });
    this.nameInput = page.getByLabel('Display name');
    this.saveButton = page.getByRole('button', { name: 'Save' });
  }

  async open() {
    await this.page.goto('https://example.test/account');
    await expect(this.heading).toBeVisible();
  }

  async changeDisplayName(name: string) {
    await this.nameInput.fill(name);
    await this.saveButton.click();
    await expect(this.saveButton).toBeDisabled();
  }
}

Use role, label, and test-id locators rather than CSS paths tied to presentation markup. Keep assertions that define the page’s ready state in the POM when they are useful to every test.

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.

Provide the POM through a fixture

Fixtures avoid constructing page objects repeatedly and make the test API read like the domain under test.

import { test as base, expect } from '@playwright/test';
import { AccountPage } from './pages/account-page';

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

export { expect };

Because the project’s storageState initializes the context, the fixture’s page is already authenticated.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { test, expect } from '../playwright/fixtures';

test('user can update the display name', async ({ accountPage }) => {
  await accountPage.open();
  await accountPage.changeDisplayName('Taylor');
  await expect(accountPage.page.getByText('Saved')).toBeVisible();
});

When to use a shared account or worker accounts

A single state file is safe only when tests can run concurrently without conflicting server-side changes and authentication is not browser-specific.

Use one shared account when

  • Tests mostly read data.
  • Writes are isolated, repeatable, or cleaned up.
  • Parallel tests cannot change the same records.

Use one account per worker when

Tests mutate shared server data, create records with unique ownership, or otherwise interfere in parallel. Playwright’s authentication guide shows selecting a state file with test.info().parallelIndex in a worker-scoped fixture. Generate those files during setup, then have each worker reuse its own state.

Use separate role states

Create files such as admin.json and user.json during setup. A test needing two simultaneous identities should create two browser contexts, each with its role’s state. Do not try to give one page two identities.

const adminContext = await browser.newContext({
  storageState: 'playwright/.auth/admin.json',
});
const userContext = await browser.newContext({
  storageState: 'playwright/.auth/user.json',
});
const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();
// ...exercise each role...
await adminContext.close();
await userContext.close();

Classic globalSetup: the compatible alternative

globalSetup is a function that runs once before the test suite. It receives FullConfig, manually launches a browser, signs in, writes state, and closes the browser.

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.
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.
import { chromium, type FullConfig } from '@playwright/test';

async function globalSetup(config: FullConfig) {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  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();
  await page.waitForURL(//dashboard/);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
  await browser.close();
}

export default globalSetup;

Configure it with globalSetup: require.resolve('./global-setup') and point projects at the resulting state file. This method has important trade-offs: it has no separate HTML-report entry, does not support test traces in the same way, cannot use normal test fixtures, and requires manual browser management. Prefer a setup project when those integrations matter.

Session storage and API authentication

Restore session storage only when required

The storage-state API does not persist session storage, which is scoped to a domain. If the application stores authentication there, capture the values and inject them before application code runs:

const session = await page.evaluate(() => ({
  token: sessionStorage.getItem('token'),
}));
// Save session as a separate JSON file, then:
await context.addInitScript((saved) => {
  for (const [key, value] of Object.entries(saved)) {
    if (value !== null) sessionStorage.setItem(key, value as string);
  }
}, session);

Adapt the keys and serialization to your application; do not assume every session value is an authentication token.

Authenticate through an API

If the application exposes a suitable login endpoint, Playwright’s API testing documentation shows using APIRequestContext to sign in and save request storage state, then reusing it in a browser context. This can be faster and less brittle than UI login, but the endpoint, payload, CSRF handling, and response format are application-specific.

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

Expiration, security, and CI operation

  • Regenerate state whenever cookies or server sessions expire. A failed setup should fail before dependent tests run.
  • Write temporary state under the test project’s outputDir when it need not survive a run; Playwright cleans that directory before each run.
  • Never commit state files, even to a private repository. Treat them like passwords.
  • Ensure CI secrets are available to the setup project and use a dedicated account with the minimum permissions required.
  • Run the setup project explicitly in UI mode when needed; the authentication guide notes that UI mode does not run the setup project by default.

Troubleshooting

Tests are redirected to login

The state was saved too early, expired, or was written to a different path. Verify the post-login URL and authenticated heading, print the resolved path, and regenerate the file.

State works in Chromium but not another browser

Cookies, user-agent assumptions, or browser-specific storage may differ. Generate and validate state with the same browser projects that consume it.

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

Parallel tests change each other’s data

Stop sharing the account for mutating tests. Use worker-specific accounts and state files keyed by parallelIndex, or serialize the conflicting tests.

A second role appears logged out

Each browser context has its own identity. Create a context with the correct role file and pass its page to that role’s POM.

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

Session-based login is missing

That is expected: session storage is not in storageState. Add an addInitScript restoration step or change the application test login to use cookies/local storage.

Setup does not appear in reports

You are probably using globalSetup. Move authentication into a setup test and declare it as a project dependency.

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

Or skip the browser setup

For generating website screenshots in automation, ScreenshotNeo provides a direct API and an MCP server instead of requiring you to maintain a Playwright capture browser. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result.

See the ScreenshotNeo API documentation for all options, including device presets, full-page capture, selectors, waits, custom headers, cookies, JavaScript, PDFs, blocking rules, caching, signed links, async jobs, and bulk capture.

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
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

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.

FAQ

Should every test call the login UI?

No. Authenticate once in setup and reuse the resulting state unless the test specifically verifies authentication itself.

Can one state file represent two users?

No. Use separate state files and browser contexts for simultaneous identities.

Is globalSetup obsolete?

No, it remains usable, but setup projects integrate more fully with Playwright’s runner, reporting, tracing, and fixtures.

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

Frequently Asked Questions

Should every test call the login UI?

No. Authenticate once in setup and reuse the resulting state unless the test specifically verifies authentication itself.

Can one state file represent two users?

No. Use separate state files and browser contexts for simultaneous identities.

Is globalSetup obsolete?

No. It remains usable, but setup projects integrate more fully with Playwright’s runner, reporting, tracing, and fixtures.

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.

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