Redirect in Try-Catch

redirect() inside try/catch — Next.js redirect throws, catch swallows it

criticalReliabilityredirect-in-try-catch

Why 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

Flaggedapp/dashboard/page.tsx
export 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>;
  }
}
Fixedapp/dashboard/page.tsx
export 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 --json and 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-catch at 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