DEV Community

Tugrul Erdem
Tugrul Erdem

Posted on

Correct Usage of redirect() with App Router in Next.js

When using (App Router) in Next.js, calling the redirect() function actually throws an exception. This is a method Next.js uses to trigger its own routing mechanism.

In other words, when you call redirect("/dashboard"), a special NEXT_REDIRECT error is thrown in the background, and the remaining code execution is stopped. This exception is caught by Next.js and the user is redirected to the specified page. There is no real error here; the redirection is successfully completed.

However, if you wrap the redirect() function inside a try/catch block, the exception will be caught by your catch block. As a result, Next.js will not be able to complete the redirection. Moreover, since the exception is usually re-thrown, it may appear as an actual error and display an error page. Therefore, the redirect() function should be called directly, outside of any try/catch block.

If you need to perform error handling before redirecting, you should throw an error only when necessary, and call redirect() directly on successful conditions.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay