In Playwright, refresh an expired session by rerunning the site’s normal sign-in flow, waiting for a reliable signed-in signal, and saving fresh browser state before the screenshot run. The exact login steps and expiration signals depend on the website; there is no universal cookie edit or refresh-token command that works for every site.
Regenerate Playwright authentication state before the screenshot run
A reliable setup separates authentication from screenshot capture. The setup signs in and writes a new state file; the screenshot test loads that file only after setup succeeds. The example below uses Playwright Test with a UI login. Replace the example URL, selectors, and success signal with the ones for your application.
1. Configure a setup project
Install Playwright Test if it is not already in the project, then create or update playwright.config.ts:
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: 'auth/state.json',
},
dependencies: ['setup'],
testIgnore: /auth.setup.ts/,
},
],
});
The setup project runs before the Chromium project. The state path is generated by the setup test below; add auth/ to .gitignore so the generated credential-bearing file is not committed.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errors#1 Best Overall
- 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.
2. Sign in, verify the result, and write fresh state
Create tests/auth.setup.ts. This example assumes a username-and-password form and an account page with a visible signed-in control. Set APP_URL, TEST_USERNAME, and TEST_PASSWORD in the environment where you run tests.
import { test as setup, expect } from '@playwright/test';
import fs from 'node:fs/promises';
const stateFile = 'auth/state.json';
setup('authenticate', async ({ page }) => {
const baseURL = process.env.APP_URL;
const username = process.env.TEST_USERNAME;
const password = process.env.TEST_PASSWORD;
if (!baseURL || !username || !password) {
throw new Error('Set APP_URL, TEST_USERNAME, and TEST_PASSWORD before running Playwright.');
}
await page.goto(new URL('/login', baseURL).toString());
await page.getByLabel('Email').fill(username);
await page.getByLabel('Password').fill(password);
await page.getByRole('button', { name: 'Sign in' }).click();
// Prefer a stable post-login signal from your application.
await expect(page).toHaveURL(//account(?:/|$)/);
await expect(page.getByRole('button', { name: 'Account menu' })).toBeVisible();
await fs.mkdir('auth', { recursive: true });
await page.context().storageState({ path: stateFile });
});
Use the final URL, a uniquely authenticated UI element, or preferably both. A page merely loading is not proof of authentication: many sites redirect back to login, show an access-denied page, or render a partially loaded account shell. If your application uses a supported authentication API instead of a UI flow, you can create the authenticated context through that application-specific route, then verify it the same way.
3. Capture only after the authenticated page is ready
Create tests/screenshot.spec.ts and use a meaningful content assertion before saving the image:
Rank #2
- 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.
import { test, expect } from '@playwright/test';
test('capture the signed-in account page', async ({ page }) => {
const baseURL = process.env.APP_URL;
if (!baseURL) throw new Error('Set APP_URL before running Playwright.');
await page.goto(new URL('/account', baseURL).toString());
await expect(page).toHaveURL(//account(?:/|$)/);
await expect(page.getByRole('button', { name: 'Account menu' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Account overview' })).toBeVisible();
await page.screenshot({ path: 'artifacts/account.png', fullPage: true });
});
Run with credentials supplied securely by your shell or CI secret store, for example:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →APP_URL=https://example.test TEST_USERNAME='test-user' TEST_PASSWORD='secret' npx playwright test
Change the URL paths and accessible names to match your app. If you use toHaveScreenshot in the Playwright test runner for visual assertions, Playwright waits for two consecutive screenshots to stabilize before comparing the final screenshot. That stabilization is specific to that assertion; it does not guarantee every page in a separate screenshot workflow has finished loading dynamic content.
Choose the right expiry check and authentication flow
Session expiration is controlled by the application’s login design and token lifetime. Detect it using a signal the site actually provides rather than assuming a particular cookie name or duration.
Rank #3
- 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.
- Login redirect: Treat a redirect to the login route as unauthenticated, including redirects that happen only after navigating to a protected page.
- Missing signed-in UI: Check for a stable account control or protected-content heading. A missing element can also indicate a selector change or a slow page, so use a bounded assertion timeout and inspect the resulting page on failure.
- Application validation: Microsoft’s Power Platform Playwright sample validates saved state before tests and prompts for reauthentication when it has expired. Its token and cookie checks are specific to that sample’s Power Platform context, not general Playwright behavior.
For a locally run suite, rerunning the setup project regenerates state before dependent tests. In CI, make the setup project a dependency of the capture project in each job that needs fresh state. If you deliberately reuse a state file between jobs, validate it and rerun authentication when the application rejects it.
Know what Playwright state does and does not persist
Playwright’s reusable storage state covers cookies, local storage, IndexedDB, and passkey (WebAuthn)-based authentication. Its standard storage-state mechanism does not persist session storage automatically. Session storage is domain-specific and does not survive page loads in the same way as a saved state file.
Free tools Windows power users keep installed
One-click scans. No signup required.
If your application relies on session storage, Playwright’s authentication guide shows a separate manual save-and-restore approach using addInitScript. Use that only after confirming the application needs it; do not assume every session uses session storage or that copying an arbitrary token into it is safe or sufficient.
Rank #4
- 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
Protect the saved state and handle parallel runs
- Treat the file like a password. Playwright warns that state files can contain cookies and headers capable of impersonating the test account and says, “We strongly discourage checking them into private or public repositories.” Keep the authentication directory out of source control and restrict access to CI artifacts and logs.
- Use a dedicated, least-privilege test account. Microsoft recommends dedicated least-privilege accounts and secret handling in its Power Platform sample. Its certificate-based authentication and Azure Key Vault recommendations apply to that sample environment; they are not requirements for every Playwright project.
- Consider account contention. One shared account may be unsuitable for parallel workers or tests that change server-side state. Separate accounts or isolated test data may be needed when concurrent runs interfere with each other.
- Refresh rather than hand-edit. When state expires, rerun the normal authentication setup and replace the generated state file. A manually changed cookie may not update related storage, server-side state, or other login factors.
Troubleshoot failed authentication or screenshots
| Symptom | Likely cause | What to check |
|---|---|---|
| Setup times out waiting for the account URL or control | Wrong success signal, failed sign-in, or slow/conditional login flow. | Inspect the final URL and page after clicking sign in; verify selectors, credentials, and any required MFA or consent steps. Choose a signal that exists only after successful authentication. |
| Setup passes, but capture is redirected to login | The saved state is incomplete, expires quickly, or the page needs storage not included in standard state. | Check whether the app uses session storage, confirm the state file is written after login completes, and verify the screenshot project loads the same path. |
| Works in one run but fails in parallel | Workers may be sharing an account whose state or server-side data is being changed concurrently. | Use separate test accounts or isolate the data and avoid simultaneous operations that invalidate one another. |
| Screenshot is blank or missing dynamic content | The navigation completed before the relevant content became available, or the page is displaying an error/expired state. | Assert the authenticated heading and target content before capture; wait for a specific selector or application-ready signal instead of relying only on navigation completion. |
| Authentication works except for one app using session storage | Standard storage-state reuse does not restore session storage. | Use the documented manual session-storage save/restore pattern only for the relevant origin, and verify the restored session with an authenticated UI assertion. |
Or skip the browser setup
If you are capturing a publicly accessible page, ScreenshotNeo can return a screenshot with one GET request. For example, using cURL:
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 documentation for request options. ScreenshotNeo accepts cookie banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; these steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.
ScreenshotNeo is a screenshot API, not a replacement for signing into an arbitrary private application: its one-call example does not reuse the Playwright state file above. For authenticated screenshots, retain the authorized browser sign-in workflow or use the API’s supported authentication options where appropriate. Learn more at ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.
Frequently Asked Questions
Should I refresh the session by editing a cookie?
No. Regenerate browser state through the application’s normal authorized sign-in flow; a cookie edit may not restore the related state the site requires.
Best Value
- 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.
Does Playwright automatically know that saved authentication has expired?
Not universally. Add an application-specific validation signal, such as a login redirect or missing authenticated control, and rerun setup when that check fails.
Will ScreenshotNeo use the Playwright session state file?
The one-call ScreenshotNeo example does not consume that file. Its example is for a publicly accessible URL; private-site authentication must be handled through an authorized supported method.
Quick Recap
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.

