Next.js Discord

Discord Forum

redirect() not working on async page or layout

Unanswered
Cinnamon posted this in #help-forum
Open in Discord
CinnamonOP
I'm trying to call redirect() in one of my layout.tsx files based on some of the request parameters. However it isn't actually redirecting the user, it's just throwing the NEXT_REDIRECT error that shows up in the dev overlay but the page continues trying to render as normal. I know that redirect intentionally throws this error to stop execution, but why is not being caught by Next.js properly? I already made sure it isn't in a try/catch.

The conditions I'm checking for are specific to the layout/route group and needs session info from NextAuth, so I want to avoid another layer of complexity by adding middleware to the app if possible. Does redirecting even work in layouts? Everything I saw online said it does.

1 Reply

CinnamonOP
Did some more testing and it actually works if I call redirect() directly in the layout code. But if the call is inside a helper function, it messes up the behavior even when that function isn't wrapped in a try/catch.