-
Notifications
You must be signed in to change notification settings - Fork 26.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ESLint Rule to Prevent Redirect in Try-Catch Block #68108
base: canary
Are you sure you want to change the base?
Conversation
Allow CI Workflow Run
Note: this should only be enabled once the PR is ready to go and can only be enabled by a maintainer |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, here's a more natural and realistic version:
- The rule shouldn't just be limited to
redirect
errors. It should cover all Next.js thrown errors, includingredirect
,notFound
,req.nextUrl.searchParams
, andprops.searchParams
. - Rather than blocking these functions, it should make sure to call
unstable_rethrow
at the beginning of the catch block.
@AhmedBaset I appreciate your suggestion regarding the scope of the rule. I can add rules for redirect and notFound in this PR, but they should probably be separate rules to keep with the convention. As for req.nextUrl.searchParams and props.searchParams, it might be better to address those in a separate PR. What do you think about this approach? Regarding the use of unstable_rethrow, I'm not entirely sure since the latest documentation for actions recommends using useActionState for error handling. You can find more details here: Next.js Error Handling Documentation. |
…nstable_rethrow`
…direct-in-try-catch-without-rethrow` and update docs
@feedthejim, apologies for the delay, and thanks for your feedback! I’ve updated the rule to enforce Quick question: should we handle |
What?
This PR introduces a new ESLint rule to prevent the use of
redirect
within a try-catch block in Next.js applications.Why?
This change was inspired by a discussion on X here. Using
redirect
within a try-catch block can prevent redirects from executing correctly becauseredirect
throws aNEXT_REDIRECT
error internally, which can be caught and handled by the catch block, thus stopping the redirect.How?
ESLint Plugin:
index.ts
to register theno-redirect-in-try-catch
rule.no-redirect-in-try-catch.ts
to define the rule logic.Testing:
no-redirect-in-try-catch.test.ts
to validate correct and incorrect usage of theredirect
function within try-catch blocks.Documentation Update:
02-eslint.mdx
to include the new rule.no-redirect-in-try-catch.mdx
to explain the new rule, why it is necessary, and how to fix violations.