Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon 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 Now×
Skip to content
World desk5 min

How to Find Broken Links with Cypress

Use DOM assertions for same-page fragments and cy.request() for HTTP destinations, with explicit rules for redirects, external sites, and actionable failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Cypress for two distinct checks: verify that same-page fragment links point to elements in the rendered document, and use cy.request() to test HTTP destinations. Treat links such as mailto: and tel: separately, and keep third-party availability checks out of deterministic UI tests unless they are an explicit monitoring requirement.

Decide what counts as a broken link

A link can fail in different ways, so define the test policy before writing assertions:

As an Amazon Associate I earn from qualifying purchases.

  • Fragment link: a same-page #pricing link should point to an element with the matching ID in the rendered document.
  • HTTP link: the destination should return an allowed status and, where needed, redirect to the expected URL or provide expected content.
  • Non-HTTP link: schemes such as mailto: and tel: are not web-page requests. Exclude them from HTTP checks or validate them under a separate policy.

A successful HTTP status alone does not prove that the destination is useful: a 200 response can still serve the wrong content. Define acceptable redirects and content for your application rather than treating every response identically.

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

Choose the right Cypress check

Check What it verifies Typical failure Stability
Fragment assertion Target element exists in the current rendered document Missing or mismatched ID Usually deterministic within the app
cy.request() HTTP response from a server endpoint Error status, timeout, or unexpected redirect Depends on the destination, especially for third parties

cy.request() makes a direct request to a running server; it does not render the destination in a browser. It bypasses browser CORS restrictions. By contrast, cy.intercept() observes, waits for, or stubs traffic made by the application; it is not a replacement for checking a destination with a direct request. See the Cypress cy.request() documentation and Cypress cy.intercept() documentation.

Check same-page fragment links

Visit a representative route, collect its anchors, and check each same-document fragment against rendered IDs. Do not assume every anchor is a fragment or that every fragment belongs to the current page: a URL may include another path as well as a fragment.

Runnable example for fragment-only links

cy.visit('/page')

cy.get('a[href^="#"]').each(($link) => {
  const href = $link.attr('href')
  const id = decodeURIComponent(href.slice(1))

  expect(id, 'fragment must not be empty').not.to.equal('')
  cy.get(`[id="${CSS.escape(id)}"]`).should('exist')
})

This checks fragment-only hrefs such as #pricing. The explicit empty-fragment assertion makes the policy visible; remove or change it if an empty fragment is intentionally allowed. If a page may have no matching anchors, avoid making the test fail merely because the collection is empty. For example, inspect the collection length and apply your chosen empty-set policy before iterating.

For a link that includes a path and fragment, resolve its href against the current page URL first. Only check the target in the current document when the resolved URL identifies that document; otherwise, the target belongs to a different page and needs a separate visit or route-specific check. Duplicate IDs are invalid HTML and can make a simple existence assertion insufficient if the application expects a unique target. Cypress’s anchor-link example demonstrates the basic target-existence approach and the need to handle pages with no anchor links.

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.

Check HTTP destinations with cy.request()

Gather HTTP hrefs from a page, normalize relative links against the current page URL, and request only destinations your test is allowed to contact. Cypress defaults to GET when no method is supplied. When failOnStatusCode is enabled (the default), 2xx and 3xx responses count as successful; redirects are followed by default. Requests require a response, and timeouts can fail when a server does not respond.

Request and assert on a destination

cy.visit('/page')

cy.get('a[href]').then(($anchors) => {
  const pageUrl = new URL('/page', Cypress.config('baseUrl'))
  const destinations = [...$anchors]
    .map((anchor) => anchor.getAttribute('href'))
    .filter((href) => href && !href.startsWith('#'))
    .map((href) => new URL(href, pageUrl))
    .filter((url) => ['http:', 'https:'].includes(url.protocol))

  destinations.forEach((url) => {
    cy.request({
      url: url.href,
      failOnStatusCode: false,
    }).then((response) => {
      expect(
        response.status,
        `HTTP status for ${url.href}`
      ).to.be.within(200, 399)
    })
  })
})

This example accepts 2xx and 3xx responses and allows the test to report its own status assertion. Because redirects are followed by default, the returned status may describe the final response rather than the original redirect. If your policy needs to distinguish redirects from their destinations, set followRedirect to false, assert the expected redirect status, and inspect redirectedToUrl. To confirm a destination is meaningful, also assert its expected final URL, response body, or another application-specific condition. Cypress’s documentation covers request options, response inspection, and redirect behavior.

When cy.request() uses a relative URL, Cypress resolves it using the visited page’s host or the configured baseUrl, depending on when the request runs. Normalizing links explicitly, as above, makes the target clear and improves failure reports. Chained assertions on the response are run once, not retried.

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

Keep third-party checks separate from core UI tests

A third-party site can throttle automated traffic, block a request, require authentication, or fail temporarily for reasons unrelated to your application. Cypress advises against visiting origins your team does not control in tests; see its cross-origin guidance. A direct cy.request() avoids browser CORS, but it does not make a remote service stable or guarantee that its policies permit automated checks.

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

Keep owned routes in the deterministic application suite. If checking external destinations is a genuine operational need, run that check separately or on a schedule and report transient failures separately from core UI regressions.

Make failures actionable

Include the source page and offending href in assertion messages or test output. Normalize relative links before reporting them, and classify failures so the right person can investigate:

  • Missing fragment target or malformed/empty fragment.
  • HTTP error status or timeout.
  • Unexpected redirect destination.
  • Unexpected response content.
  • Excluded non-HTTP scheme or intentionally skipped external destination.

Cypress provides the request and assertion building blocks; it does not provide a built-in broken-link checker. The test should encode your application’s rules for routes, redirects, allowed schemes, and external dependencies.

Or skip the browser setup

For capturing a website image or PDF rather than testing link validity, ScreenshotNeo is a website screenshot API and MCP server for developers. A single GET request can return a PNG, JPEG, WebP, or PDF; it does not replace the DOM and HTTP assertions above.

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 request options. Before capture, it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and 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 1,000 free screenshots a month, with no card required.

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
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.