How to test redirect with Cypress

On This Page What is Redirecting to a different URL?January 05, 2026 · 9 min read · Tool Comparison

How to quiz redirect with Cypress

URL redirection is a standard technique in web development that post users from one address to another, frequently due to changes in page structure, authentication requirements, or legacy link handling.

While redirects are easy to implement, failing to examine them properly can cause user to land on the wrong page, encounter unexpected behavior, or trigger SEO issues.

This article excuse how to test URL redirects employ Cypress. It covers redirection, when it occurs, why it count, and how to formalise response code like 301, 200, and 404. It too outlines good practices for accurate and maintainable redirect testing.

What is Redirecting to a different URL?

Redirecting to a different URL occurs when a web coating automatically sends a user from one endpoint to another. This behavior is typically triggered by server-side or client-side logic ground on specific conditions, such as user hallmark, form submissions, routing changes, or URL restructuring.

Redirects serve multiple purposes, such as contend broken links, consolidating duplicate content, enforce HTTPS or canonical URLs, and deal site migrations.

From a user perspective, redirects check a unseamed experience by leading them to the correct content. For lookup locomotive, redirects help maintain indexing accuracy and preserve SEO value by transplant link fairness from the old URL to the new one.

There are several case of redirects, with the most common be:

  • 301 (Moved Permanently):Indicates that a resource has been permanently moved to a new URL.
  • 302/307 (Found/Temporary Redirect):Used for temporary redirections.
  • Meta Refresh or JavaScript-based Redirects:Client-side methods, broadly less SEO-friendly.

Read More:

Because redirect behavior, especially client-side, can vary across browser, device, and network conditions, it ’ s essential to prove redirects in real-world environment.

Cypress, a powerful framework, helps automate redirect testing, assure functionality act as require. By integrating with instrument like, teams can run these trial across a wide range of real browsers and devices, catching environment-specific issues before they affect users.

Cases / Scenarios where you have to redirect the exploiter to a new URL

Here are some of the scenarios where Redirect to a new URL is most commonly habituate:

  1. In the case that the original URL is no longer active, forth traffic to the new URL.
  2. Shift authority when backlinks lead to a relocate page
  3. Enhance the general user experience by preventing visitors from landing on broken or duplicate pages.
  4. The loss of search engine ranking and customer dissatisfaction can result from drop to use redirects.
  5. Consider moving or deleting a web page without first fix up a redirect. The site will answer with a 404 fault for users. Thus making for a frustrative encounter for the user. That detracts from a satisfying interaction for the consumer. When users encounter a 404 error, they may decide to abandon your site.
  6. You obviate a page.
  7. Parent sites or category tags you add have an encroachment on URLs.
  8. Your page is transferred to a new field.
  9. Your site is undergoing repair.
  10. Combining two or more identical web Page
  11. Your website is converted from HTTP to HTTPS.

Read More:

Why it is crucial to Test Redirect to a new URL with Cypress

Your app & # 8217; s end users will only ever access your site through a small fistful of preset URLs. Alternatively, they may frequently fail to include the & # 8220;www.& # 8221; or & # 8220;s& # 8221; in & # 8220;https://,& # 8221; resulting in an wrong initialize URL.

With Cypress test redirect, you can test a smorgasbord of tasks that are typically done with300 or 301redirects from the servers, as well as test user responses to404 or 500forbidden page.

Redirects 301 code

Redirects typically use the 301 — & # 8220;Moved Permanently& # 8221; — codification. They are apply when a especial website or URL has be moved to another location or reorganized.

const baseUrlTesla = `` https: //www.browserstack.com/ ''; const urlHttp = `` http: //browserstack.com ''; it (urlHttp + `` end location '', () = & gt; {cy.visit (urlHttp); cy.url () .should (`` eq '', baseUrlTesla);}); it (urlHttp + `` redirect '', () = & gt; {cy.request ({url: urlHttp, followRedirect: false, // become off following redirects}) .then ((resp) = & gt; {// redirect status code is 301 expect (resp.status) .to.eq (301); expect (resp.redirectedToUrl) .to.eq (baseUrlTesla);});});

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Found Page 200 code

When the server exactly situate the resource at the URL you indicated in your request, the & # 8220;200& # 8221; response codification is used for all plant Page.

const baseUrlTesla = `` https: //www.browserstack.com/ ''; const urlHttpsWww = `` https: //www.browserstack.com/ ''; it (urlHttpsWww + `` end locating '', () = & gt; {cy.visit (urlHttpsWww); cy.url () .should (`` eq '', baseUrlTesla);}); it (`` 200 homepage response '', () = & gt; {cy.request ({url: urlHttpsWww, followRedirect: false,}) .then ((resp) = & gt; {ask (resp.status) .to.eq (200); look (resp.redirectedToUrl) .to.eq (vague);});});

Not Found Page 404 code

You will see the about stunning and typical code 404, also known as & # 8220; not found, & # 8221; when a page can not be place.

const baseUrlTesla = `` https: //www.browserstack.com/ ''; const url404test = `` https: //www.browserstack.com/not-a-real-page ''; it (`` 404 'not found ' response '', () = & gt; {cy.request ({url: url404test, followRedirect: false, failOnStatusCode: false,}) .then ((resp) = & gt; {wait (resp.status) .to.eq (404); expect (resp.redirectedToUrl) .to.eq (undefined);}); cy.visit (url404test, {failOnStatusCode: false}); cy.get (`` .error-code '') .should (`` contain '', `` 404 ''); cy.get (`` .error-text '') .should (`` contain '', `` Page not constitute '');});

How to test redirect with Cypress (with instance)

Now you & # 8217; ll fabricate a verification redirect test case that will be point at a specified web address. The procedure hither is to substitute a new URL and then verify the title.

For testing the redirect feature, use the object structure below. You & # 8217; ll receive these data afterward from a JSON file.

{'' title '': `` TITLE OF THE ARTICLE '', '' from '': `` OLD URL '', '' to '': `` NEW URL ''}

Create a & # 8220; website-redirect & # 8221; brochure in the & # 8220; cypress/integration & # 8221; folder and add a examination case to it. This test case validates the redirect lineament.

describe (`` website redirects '', () = & gt; {it (`` webpage redirect '', () = & gt; {const page = {'' title '': `` Why is Espresso preferred for Android UI Testing? ``, '' from '': `` https: //www.browserstack.com/android-ui-testing-espresso '', '' to '': `` https: //www.browserstack.com/guide/android-ui-testing-espresso ''} cy.visit (page.from, {failOnStatusCode: false}); cy.url () .should (`` be.equals '', page.to) cy.title () .should (`` include '', page.title);});});

The page.fromvalue is used in thecy.visit (page.from)function to admittance a page with a URL. In order to set the spare option for loading the page in the browser, you can use the options argument. If the response code is not & # 8220;2XX& # 8221; or & # 8220;3XX, & # 8221; thefailOnStatusCode: falsewouldn & # 8217; t fail the test.

To check if the URL was vary following the redirect, you can usecy.url()to get the current URL of the site. By callingcy.title (), you can retrieve the rubric from the current page & # 8217; sdocument.title.

Though efficient, this method is hindered by the front of a page object in your test scenario. Put this page object in a different JSON file so that it can be used as test datum. The & # 8220;fixtures& # 8221; directory, which is typically used to laden a solicitation of datum stored in a file, is already present in the predefined construction of the & # 8220; cypress & # 8221; pamphlet. You can put your redirect-data.json file thither precisely fine.

[{'' rubric '': `` Why is Espresso preferred for Android UI Testing? ``, '' from '': `` https: //www.browserstack.com/android-ui-testing-espresso '', '' to '': `` https: //www.browserstack.com/guide/android-ui-testing-espresso ''}, {'' title '': `` How to do Parallel Test Execution in Appium? ``, '' from '': `` https: //www.browserstack.com/parallel-test-execution-appium '', '' to '': `` https: //www.browserstack.com/guide/parallel-test-execution-appium ''}, ...]

There are respective method to load an array for your test cases when a JSON file is created:

  • A set collection of datum stored in a file is loaded by thecy.fixture (filePath)function. You can make use of this choice within the test case.
  • The JSON file can be loaded and use for data outside of the test case employ the require/import.

The second choice is preferred for you because it allows you to build numerous tests using an regalia of JSON file objects. In this situation, you can use the name of the page as the tryout case & # 8217; s name.

import data from ' .. / .. /fixtures/redirect-data.json '; describe (`` website redirects '', () = & gt; {data.forEach (pageObj = & gt; {it (` redirect of `` $ {pageObj.title} '' page `, () = & gt; {cy.visit (pageObj.from, {failOnStatusCode: false}); cy.url () .should (`` be.equals '', pageObj.to) cy.title () .should (`` include '', page.title);});});});

The titles of the pages will be used in your report when the array contains numerous value.

Read More:

Good Practices for Testing Redirect in Cypress

To ensure reliable and effective redirect prove in Cypress, consider the undermentioned best practices.

  • Better exercise for lookup locomotive optimization when redirecting a URL include sending the user to Page that are both similar to and pertinent to the original. It & # 8217; s poor form to send user to pages that are unrelated to the original and serve no useful purpose.
  • Chains of redirects are easy to make and should be deflect. Chain links can induce a lot of extra hop that the user might not even notice, but search engines do. Screaming Frog is a utilitarian instrument for see chain of redirects. When Google meet a certain number of 301 redirects, it stops crawling the site entirely, and the new URL is ne'er expose.
  • Check to see that all of your internal links have been update. Having incorrect internal links can considerably slow down a website, so truth is essential. Websites should minimize the use of redirects as lots as viable. It & # 8217; s always possible that lounge nexus will lead to intractable problems on a site.
  • Do not use soft 404s. A redirect to an unrelated website will be watch by Google as a soft 404. This indicates that Google won & # 8217; t transmit page authority and will disregard the redirect.
  • Periodic 404 erroneousness are acceptable. When a page doesn & # 8217; t live on a new site & # 8217; s equivalent, it may be essential to leave it as a 404. When you do feature them, it & # 8217; s good to make a personalized 404 page with contact info or useful links can yield a user value.

To validate redirect behavior across different browsers, devices, and operate system, consider running your Cypress exam on using. It proffer access to 3500+ existent browser and device combinations, supports executing for faster feedback, and integrates seamlessly with Cypress through its CLI.

This aid teams get inconsistencies that may not appear in local examine setup and control a coherent user experience across platforms.

Talk to an Expert

Conclusion

The power to reroute visitors is a common feature of many websites. Regular tasks like checking redirects, looking up articles, signing up for newssheet, etc., can be perform quickly and easily with the help of test automation.

One of the many tools that supports you in performing these confirmation is Cypress. If you ’ re using a content management scheme (CMS) like WordPress, Ghost, or a turn of others, this can be a agile and simple way to ensure all redirects are functioning properly.

Cypress exam can be executed on real browser environments across Windows and macOS using BrowserStack. By simulating existent user interactions it helps squad identify issues before they reach end users.

To check software performs reliably under, such as, low battery, or interruptions like incoming calls, testing on actual devices is essential. If maintaining an in-house isn ’ t feasible, a is the better choice.

BrowserStack provides access to 3500+ existent device and browsers, allowing teams to run Cypress tryout across a wide range of desktop and mobile surroundings. This control exact, comprehensive testing and a consistent exploiter experience across platforms.

Tags
90,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free