Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › authentication

How to Take Cypress Screenshots of a Website Behind Login

By Freedom251 Team · · 6 min read

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

Log in first, confirm the authenticated session, visit the protected page, and then call cy.screenshot(). Cypress screenshots capture the page currently loaded in the test; they do not sign you in. For repeatable tests, cache and validate login state with cy.session(), then explicitly navigate to the page you want to capture.

Set up authentication before capturing

For a protected-page screenshot, the test needs a valid login state and a reliable check that the application accepted it. Cypress documents both UI-based login and API-based login. An API request is often the faster setup when your application provides a suitable test login endpoint; a UI flow also exercises the user-facing login journey. Cypress API testing

As an Amazon Associate I earn from qualifying purchases.

Reusable API login with cy.session()

This example assumes the application accepts a POST to /api/login, uses cookie-based authentication, exposes /api/me for validation, and serves the account page at /account. Replace those paths and assertions to match your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const loginAs = (username) => {
  cy.session(username, () => {
    cy.request('POST', '/api/login', {
      username,
      password: Cypress.env('TEST_PASSWORD'),
    })
  }, {
    validate() {
      cy.request('/api/me').its('status').should('eq', 200)
    },
  })
}

describe('authenticated page screenshots', () => {
  it('captures the account page', () => {
    loginAs(Cypress.env('TEST_USERNAME'))
    cy.visit('/account')
    cy.contains('Account').should('be.visible')
    cy.screenshot('account-page', { capture: 'viewport' })
  })
})

Keep credentials in Cypress environment configuration rather than embedding them in the spec. Use a non-sensitive session ID such as a username or role: Cypress displays session IDs in the reporter and advises against putting passwords or tokens in them. Cypress cy.session() API

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB | 1920×1080 LED Monitor, 4ms GtG, Adaptive Sync, HDMI 1.4, Tilt Adjust, Low Blue Light, 4yr Advance Replacement Warranty
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

When the application requires UI login

If there is no appropriate test authentication endpoint, perform the ordinary login flow inside the session setup callback: visit the login page, fill in the fields, submit the form, and assert a successful login before the callback completes. Cypress’s session documentation includes both login-via-page and login-via-API patterns. Keep the validation callback meaningful for your application, such as requesting the current-user endpoint or checking an authenticated-only page after restoration.

Restore the session and visit the page you need

cy.session() stores and restores cookies, localStorage, and sessionStorage; it does not choose or load the screenshot target. With test isolation enabled, Cypress clears the page as well as cookies and web storage before session setup. After the session has been restored, call cy.visit() for the protected route.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB | 1920×1080 LED Monitor, 4ms GtG, Adaptive Sync, HDMI 1.4, Tilt Adjust, Low Blue Light, 4yr Advance Replacement Warranty
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

The validate callback checks that a restored session remains usable. If validation fails after restoration, Cypress reruns the setup function; if validation fails immediately after setup, the test fails. A separate assertion on a distinctive authenticated-page element is still valuable: it catches redirects or application states that would otherwise produce a plausible-looking login-page screenshot.

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

cacheAcrossSpecs: true can reuse a session across specs only within one Cypress run on the same machine. A new run starts without that cached session, and separate parallel CI machines each establish their own session. Cypress cy.session() API

Rank #3
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Choose what Cypress captures

Capture Use it for Example
Viewport The visible browser viewport after the target page is ready. cy.screenshot('account-page', { capture: 'viewport' })
Full page The application from top to bottom. cy.screenshot('account-page', { capture: 'fullPage' })
Runner Debugging context that includes the Cypress runner. cy.screenshot('account-page', { capture: 'runner' })
Element A particular component or region selected by a locator. cy.get('[data-testid="account-summary"]').screenshot()

For an element capture, use a selector that identifies the intended component reliably, preferably one designed for tests rather than a fragile styling selector. Cypress’s screenshot command documentation describes capture modes, options, and element screenshots. cy.screenshot()

Protect private information in screenshot artifacts

The blackout option can hide selected elements in supported application captures, but it does not apply to runner captures. Cypress also forces automatic failure screenshots into runner mode. Do not assume that a blackout selector will redact sensitive material from every screenshot type; review artifacts before sharing or uploading them, especially when pages can show personal data, account details, or tokens. cy.screenshot() Cypress.Screenshot

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor | 100Hz, Game Mode, Advanced Eye Comfort, HDMI and D-sub Ports (LS27D366GANXZA)
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Make screenshots deterministic and keep the files

Wait for the right page state

Make assertions on the target content before capture rather than relying on navigation alone. Cypress documents screenshot capture as asynchronous and taking around 100 ms; page content can change during that interval. Cypress disables timers and animations by default while capturing to reduce movement, but that does not replace waiting for the content your test intends to show.

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

Know where output goes

Screenshots default to cypress/screenshots. A named screenshot is saved under the adjusted spec path. If duplicate names occur, Cypress increments the filename unless overwrite: true is used. Before cypress run, Cypress clears the screenshots folder by default; set trashAssetsBeforeRuns: false in configuration if preserving that folder across runs is intentional. Cypress screenshots and videos guide cy.screenshot()

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use screenshots in interactive mode and CI

You can take manual screenshots with both cypress open and cypress run. Cypress automatically captures a failure screenshot in cypress run, including CI, but not in cypress open. Set screenshotOnRunFailure: false to disable failure captures. Configure the output directory with screenshotsFolder; its default is cypress/screenshots. Cypress Cloud can display screenshots from a CI run, or you can export them using your CI provider’s artifact mechanism. Cypress screenshots and videos guide Cypress configuration

Troubleshoot missing or incorrect captures

  • The screenshot shows a login page. The session may be expired, setup may not have authenticated successfully, or the app redirected after the visit. Check the cy.session() validation request and assert a distinctive element on the protected page before capture.
  • The session restores, but the target page is blank or wrong. Restoring session data does not navigate to the target. Call cy.visit('/account') after loginAs(), then wait for the expected page content.
  • Login setup runs repeatedly. The session may not be passing validation, or its ID may differ between calls. Use a stable, non-secret identity for the ID and confirm the validation endpoint accurately reflects an authenticated session.
  • A session is missing on another CI worker or run. Cross-spec caching is limited to one run on one machine. Parallel machines and later runs need to establish their own session.
  • Sensitive content is visible despite blackout. Blackout does not apply to runner screenshots, including automatic failure captures. Avoid runner capture for shareable redacted output and review artifacts before distributing them.
  • An old screenshot disappeared after running tests. Cypress clears the screenshot folder before cypress run by default. Set trashAssetsBeforeRuns: false if preserving existing files is intentional, or export artifacts as part of CI.

Or skip the browser setup

For a public page that does not require your authenticated browser session, ScreenshotNeo can return an image or PDF from one request. It is a screenshot API and MCP server for developers: cookie and consent banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, and cache hits are not billed; and AI agents can use its MCP server. Free includes 1,000 screenshots per month without a card, and paid plans start at $5 for 3,000.

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. This is an alternative for publicly reachable pages, not a way to reuse the Cypress browser’s private login session. ScreenshotNeo offers plans with every feature on every plan. Sign up for 1,000 free screenshots a month with no card.

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

Frequently Asked Questions

Does cy.screenshot() log in to a protected site?

No. The test must establish and verify authentication before visiting the protected page and capturing it.

Can I use cy.session() across separate Cypress runs?

No. Cross-spec reuse with cacheAcrossSpecs is limited to a single run on the same machine; each new run starts without that cached session.

Will blackout hide private data in every Cypress screenshot?

No. Blackout does not apply to runner captures, including automatic failure screenshots.

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.

authenticationCICypressscreenshotsweb testing

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.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.