Handling Next.js Server-Side action Redirects in Cypress Tests

When working with Next.js server-side actions, it is often required to perform redirects for various reasons, such as user authentication, conditional rendering, or route changes based on server-side logic. These redirects can pose a challenge when running end-to-end tests using Cypress. By default, Cypress fails tests if it encounters uncaught exceptions, including those triggered by Next.js server-side redirects. In this blog post, we'll explore why and how to handle these exceptions to ensure your Cypress tests run smoothly.

The Challenge: NEXT_REDIRECT Exceptions

When performing a server-side redirect in Next.js, the redirect() function is often used. This function triggers a NEXT_REDIRECT error, which Next.js expects and handles internally to perform the actual redirect. However, these exceptions can cause Cypress tests to fail if not handled properly, as Cypress considers any uncaught exception a failure.

The Solution: Handling NEXT_REDIRECT Exceptions in Cypress

To ensure that your Cypress tests do not fail due to these expected redirects, you need to instruct Cypress to ignore NEXT_REDIRECT exceptions. This can be achieved by adding a custom handler for uncaught exceptions in your Cypress test, to add it to your support/commands.js file if you want to apply to all tests.

// Cypress configuration to handle uncaught exceptions related to NEXT_REDIRECT
Cypress.on("uncaught:exception", (err) => {
    console.log("err.message", err.message);

    // Check if the error message includes "NEXT_REDIRECT"
    if (err.message.includes("NEXT_REDIRECT")) {
        // This block is added to handle server-side redirects in Next.js.
        // Next.js often performs server-side redirects for various reasons, such as:
        // - Authentication flows (redirecting to login page if not authenticated)
        // - Conditional rendering based on user data
        // - Route changes based on server-side logic
        // When these redirects occur, they can throw a "NEXT_REDIRECT" error, 
        // which is expected behavior and should not cause the test to fail.
        // Returning false here prevents Cypress from failing the test when such an error is encountered.
        return false;
    }
});
You've successfully subscribed to Twisted Brackets
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.