Next.js

next/redirect-outside-try

Call redirect(), notFound() and their kin outside try blocks; they work by throwing, and a catch swallows them.

seriousstaticfe-nextjs

Why

redirect(), permanentRedirect(), notFound(), forbidden() and unauthorized() throw a special error that Next.js catches to change the response. Inside a try whose catch handles every error, that signal is caught by your code instead: the user stays on the page, sees a generic error message, or the action reports a failure after it succeeded.

Fix

Do the risky work inside try, keep the result in a variable, and call redirect() after the try/catch. If the call must stay inside, call unstable_rethrow(error) first in the catch, or rethrow what you do not handle.

Examples

// bad
try { await createPost(data); redirect('/posts') } catch (error) { return { message: 'Could not save' } }
// good
try { await createPost(data) } catch (error) { return { message: 'Could not save' } }
revalidatePath('/posts')
redirect('/posts')

Sources

Facts

Id
next/redirect-outside-try
Severity
serious
Check
static checked in the source by audit
Applies to
jsx
Only in projects with
next
Taught by the skill
fe-nextjs Next.js App Router
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain next/redirect-outside-try