Next.js Discord

Discord Forum

"Seeking Insight on NEXT_REDIRECT Error in Next.js Project"

Answered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
Hi all, I'm encountering a NEXT_REDIRECT error in my Next.js project:
Validation failed: Error: NEXT_REDIRECT
at getRedirectError (webpack-internal:///(actionBrowser)/./node_modules/next/dist/client/components/redirect.js:40:19)
at redirect (webpack-internal:///(actionBrowser)/./node_modules/next/dist/client/components/redirect.js:50:11)
at newReview (webpack-internal:///(actionBrowser)/./app/(formlayout)/new/action.tsx:39:73)

i found this part to be the problem:
import {redirect} from "next/navigation";
import {revalidatePath} from "next/cache";
...

export async function newReview(data: FormData) {
    ...
    try {
        const parsedData = dataSchema.parse(formValues);
        await createReview(parsedData);
        revalidatePath("/");
        return redirect('/');
    } catch (error) {
        console.error('Validation failed:', error);
        throw error;
    }
}

On form submit, it revalidates /new and stays on the same page. The error only occurs in the catch block. I'm utilizing server actions in the app directory. It also happened to my other part of the code that worked similar. I'd appreciate any insights. Thanks!
Answered by joulev & fuma pray for Schneider
you can use [isRedirectError](https://github.com/vercel/next.js/blob/ce42a999f46980f3016184c7c98c00b2f587f8f8/packages/next/src/client/components/redirect.ts#L65) to skip console.error'ing the error in that catch block. but no matter how you refactor that code, do not forget to ensure that redirect and notFound, if caught inside a catch, must be thrown again
View full answer

3 Replies

Avatar
joulev & fuma pray for Schneider
that's because redirect is essentially
function redirect() {
  throw NEXT_REDIRECT;
}

redirect and notFound throws special errors to signal to the router to change route while immediately suspending other computational work in the router (this is documented, check the documentation of these two functions)

and since it's an error, it's caught by your catch
Avatar
joulev & fuma pray for Schneider
you can use [isRedirectError](https://github.com/vercel/next.js/blob/ce42a999f46980f3016184c7c98c00b2f587f8f8/packages/next/src/client/components/redirect.ts#L65) to skip console.error'ing the error in that catch block. but no matter how you refactor that code, do not forget to ensure that redirect and notFound, if caught inside a catch, must be thrown again
Answer
Avatar
Asian black bearOP
my case: usage of (layout1) hidden directory's was wrong, i used 2 hidden directory's in the root so it could not find the page.tsx in the file i redirected to.