Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Capture Screenshots of Authenticated Pages with a Rotating CSRF Token

A reliable authenticated screenshot starts with the application’s normal login flow. Learn when to log in fresh, reuse Playwright state, and recover from rotating-token failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a real browser session that completes the site’s normal login flow, then capture the protected page in that same authenticated context. Don’t copy a CSRF token once and reuse it indefinitely: the application may rotate it, and only the application’s own flow can reliably obtain the current value. With Playwright, you can either log in for every capture or save and reload browser state for repeat runs.

How do I take a screenshot of a page after logging in?

Automate the normal login in a browser, confirm that login has completed, and navigate to the protected page in the same browser context. Let the site’s JavaScript and form handling manage its CSRF token. A screenshot of a page is different from submitting a form or performing another state-changing action; those interactions may trigger requests that need a current, valid token.

As an Amazon Associate I earn from qualifying purchases.

Playwright’s authentication guide shows how to sign in, verify the authenticated state, and save browser state for later runs: Playwright authentication. The following example uses environment variables for credentials and selectors, so secrets need not be embedded in the script.

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

Fresh login for every capture

Save this as capture.mjs. Install Playwright with npm install playwright and install its browser with npx playwright install chromium. Set the environment variables to match your application, then run node capture.mjs.

#1 Best Overall
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.
import { chromium } from 'playwright';

const {
  LOGIN_URL,
  TARGET_URL,
  USERNAME,
  PASSWORD,
  USERNAME_SELECTOR,
  PASSWORD_SELECTOR,
  SUBMIT_SELECTOR,
  SIGNED_IN_SELECTOR,
} = process.env;

for (const [name, value] of Object.entries({
  LOGIN_URL, TARGET_URL, USERNAME, PASSWORD,
  USERNAME_SELECTOR, PASSWORD_SELECTOR, SUBMIT_SELECTOR, SIGNED_IN_SELECTOR,
})) {
  if (!value) throw new Error(`Missing environment variable: ${name}`);
}

const browser = await chromium.launch({ headless: true });
try {
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto(LOGIN_URL, { waitUntil: 'domcontentloaded' });
  await page.locator(USERNAME_SELECTOR).fill(USERNAME);
  await page.locator(PASSWORD_SELECTOR).fill(PASSWORD);
  await page.locator(SUBMIT_SELECTOR).click();

  // Use a reliable signed-in indicator, not an arbitrary fixed delay.
  await page.locator(SIGNED_IN_SELECTOR).waitFor({ state: 'visible' });

  await page.goto(TARGET_URL, { waitUntil: 'domcontentloaded' });
  await page.screenshot({ path: 'authenticated-page.png', fullPage: true });
} finally {
  await browser.close();
}

Supply selectors that fit the login page and choose a signed-in element that appears only after successful authentication. If login ends at a known URL instead, wait for that URL with Playwright’s URL wait rather than relying on a time delay. For pages whose content loads asynchronously, wait for a page-specific element before capturing.

How can I keep a screenshot script authenticated?

For repeated captures, sign in once, save Playwright’s supported browser state, and load it into a new context later. This avoids re-entering credentials on every run, but a saved session can expire or become invalid. Playwright documents storage state for cookies, local storage, IndexedDB, and passkey-based authentication; sessionStorage is not included and must be saved and restored separately if the application depends on it. See Playwright’s authentication guidance.

Rank #2
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

Create the saved state

Use the same login and completion checks as in the fresh-login example, then save state only after authentication succeeds:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.locator(SIGNED_IN_SELECTOR).waitFor({ state: 'visible' });
await context.storageState({ path: 'playwright/.auth/user.json' });

Load state in a later capture

Create a fresh context from the saved state, then visit the page. This example assumes your application’s required session data is covered by Playwright storage state:

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts
import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: true });
try {
  const context = await browser.newContext({
    storageState: 'playwright/.auth/user.json',
  });
  const page = await context.newPage();
  await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' });
  await page.locator(process.env.PAGE_READY_SELECTOR).waitFor({ state: 'visible' });
  await page.screenshot({ path: 'authenticated-page.png', fullPage: true });
} finally {
  await browser.close();
}

Keep the state file out of version control. Playwright warns that it may contain sensitive cookies and headers usable to impersonate the account. Store it with access controls appropriate for credentials, limit who and what can read it, and replace it if it is exposed. Do not put CSRF tokens in URLs or logs.

Choose the state strategy for your application

Approach Useful when Trade-offs
Fresh login for each capture You want each run to follow the normal login flow or saved sessions expire frequently. Repeats authentication work; the flow may involve additional steps such as multifactor authentication.
Saved browser state Repeated captures can reuse a session and your application’s required state is supported or separately restored. The state can expire, sessionStorage requires separate handling, and the file is sensitive.

Before sharing one saved state across captures, consider its lifetime, whether the app relies on sessionStorage, whether authentication is browser- or account-specific, and whether any capture interaction changes server-side state. Playwright cautions that shared authentication may not suit tests that modify server state or require different accounts.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Why does my CSRF token expire or change?

CSRF defenses help a server distinguish a legitimate request associated with a user’s session from an unwanted cross-site request. OWASP’s synchronizer-token guidance describes tokens generated once per session or per request, with the server rejecting a missing token or one that does not match the session. Per-request rotation can reduce the window in which a stolen token is useful, but a stale page may then fail when submitted. See the OWASP Cross-Site Request Forgery Prevention Cheat Sheet.

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

For screenshot automation, avoid extracting a token once and carrying it forward as a fixed value. A page navigation for a screenshot may not itself submit a state-changing request, but application scripts or interactions can make requests. Following the ordinary browser flow gives the application a chance to provide and submit the token it currently expects; the exact behavior depends on the site’s implementation.

Best Value
FIDO2 U2F Security Key Passkey Two-Factor Authentication (2FA) USB Key PIN+Touch (Non-Biometric) USB-A Type TrustKey T110
  • Security Key : Protect your online accounts against unauthorized access by using FIDO2 and U2F authentication with T110. It's the world's most protective security key that works with windows, Mac OS, Linux as well as Chrome, Firefox, Edge and many other major browsers.
  • Certified with the new FIDO2 standard, T110 provides the benefit of fast login and strong protection against phishing, account takeover as well as many other online attactks.
  • Works with : Bank of America, Github, Google, Microsoft, DUO, Twitter, Facebook, Dropbox, Apple, ebay, BINANCE, mor and more.
  • Fits USB-A port : Insert the T110 security key into the USB-A port of each service and log in conveniently with one touch
  • For the driver download and user guide, please visit TrustKey Solutions Home support page.

OWASP states: “A CSRF token must not be leaked in the server logs or in the URL.” Tokens may be returned in HTML or JSON and sent back in form fields or custom headers, so avoid logging request details that expose them as well as placing them in query strings.

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

Troubleshooting authentication and CSRF failures

  • The capture shows the login page. The login may have failed, the signed-in check may be too weak, or the saved session may have expired. Verify the final URL and a reliable signed-in element; for saved-state runs, return to the normal login flow and refresh the state.
  • A request fails with a CSRF or token-validation error. The page or token may be stale, or a prior request may have rotated the token. Revisit the page through the normal application flow and let its code refresh the token. Do not assume that replaying an old value will work.
  • Cookies appear to load, but the app is signed out. The app may also rely on local storage, IndexedDB, sessionStorage, or another authentication mechanism. Check which storage the application uses; Playwright does not include sessionStorage in its standard storage-state file.
  • Login succeeds, but the screenshot is blank or incomplete. Authentication completion and page rendering are separate conditions. Wait for a target-page element that indicates its content is ready; a fixed sleep can be unreliable when load times vary.
  • The saved-state approach works intermittently. Session lifetime, account policies, browser-specific state, or server-side changes can invalidate reuse. Prefer fresh login when repeatability matters more than authentication speed, or refresh saved state through login when the app rejects it.
  • A shared state causes test interference. Captures that submit forms or otherwise modify server state can affect later runs. Use separate accounts or isolated state where tests require different data or independent sessions.
  • The state file is exposed. Treat it like a password: remove it from public or shared locations, revoke or invalidate the associated session if possible, and regenerate state securely.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. Its API is a one-request option for pages that are publicly accessible to the service; it is not a replacement for completing a private site’s login flow in an authenticated browser context. For an authorized page that can be reached by the API, a basic capture looks like this:

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. Cookie banners, popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000. Sign up for free.

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

Frequently Asked Questions

Does taking a screenshot itself require a CSRF token?

A screenshot of a rendered page does not necessarily submit a state-changing request. The page’s scripts or any interactions performed before capture may make requests that require a valid token.

Can I save a CSRF token and reuse it with Playwright?

Do not assume it remains valid. Token lifetime and rotation are application-specific; let the site’s normal browser flow provide the value needed for each request.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.