#NEXT_REDIRECT error
1 messages · Page 1 of 1 (latest)
The redirect function in Next.js works by throwing a special type of error that Next.js can handle. This error is caught by Next.js and it then performs the redirection. This is why you're seeing the NEXT_REDIRECT error. It's not an error in the traditional sense, but rather a mechanism for handling redirections.
However, if you're using the redirect function inside a try/catch block, the catch block will catch the NEXT_REDIRECT error before Next.js has a chance to handle it. This is likely the cause of the issue you're experiencing.
To solve this, you can use the isRedirectError function to check if the error is a redirect error in your catch block. If it is, you can simply re-throw it so that Next.js can handle it. Here's an example:
import { isRedirectError } from "next/dist/client/components/redirect";
import { redirect } from "next/navigation";
try {
// Your code here...
redirect("/profile/overview");
} catch (error) {
if (isRedirectError(error)) {
throw error; // Re-throw the error if it's a redirect error
}
// Handle other errors here...
}
Please note that the redirect function does not return a value, so it should not be used in a context where a return value is expected.
Sources:
- Github Issue (closed): redirect inside try/catch block in server action throws NEXT_REDIRECT error (https://github.com/vercel/next.js/issues/59930)
- Next.js > Docs > App > Api-reference > Functions > redirect > Returns (https://nextjs.org/docs/app/api-reference/functions/redirect#returns)
- Github Issue (closed): Next Redirect - Server action redirects do not execute when inside try / catch blocks (https://github.com/vercel/next.js/issues/55586)