Redirect in Try-Catch
redirect() inside try/catch — Next.js redirect throws, catch swallows it
criticalReliability
redirect-in-try-catchWhy this matters
Next.js redirect() works by throwing a special error. If it's inside a try/catch, the catch block swallows the redirect and the user stays on the current page.
Example
app/dashboard/page.tsxexport default async function Page() {
try {
const session = await getSession();
if (!session) {
redirect("/login"); // Caught by catch!
}
const data = await fetchData();
return <Dashboard data={data} />;
} catch (error) {
return <p>Something went wrong</p>;
}
}app/dashboard/page.tsxexport default async function Page() {
const session = await getSession();
if (!session) {
redirect("/login"); // Outside try/catch
}
try {
const data = await fetchData();
return <Dashboard data={data} />;
} catch (error) {
return <p>Something went wrong</p>;
}
}How to fix
Move redirect() calls outside of try/catch blocks. In Next.js, you can also check for the NEXT_REDIRECT error type and re-throw it.
Reference
- In the output
- Findings carry
"ruleId": "redirect-in-try-catch"in--jsonand the same id in SARIF and in the terminal. - Silence one line
// prodlint-disable-next-line redirect-in-try-catch- Silence a whole file
// prodlint-disable redirect-in-try-catchat the top of the file- How it works
- Reads the syntax tree, with a text fallback for files that don't parse. Source on GitHub