Skip to content
Watch the complete Next.js 15 course on YouTube

Recovering from errors

This page explains how to implement error recovery and retry mechanisms in Next.js using the error boundary’s reset function.

Error recovery

While error boundaries help handle errors gracefully, some errors are temporary and can be resolved with a retry. Next.js provides built-in functionality to recover from such errors through the error boundary’s reset function.

Using the reset function

The error boundary in error.tsx provides a reset function alongside the error object:

app/blog/error.tsx
"use client";
export default function ErrorBoundary({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<div>
<h2>Something went wrong!</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
);
}

Clicking the “Try again” button triggers the reset function, which attempts to re-render the component in page.tsx. However, the retry happens client-side by default.

Server-side recovery

For server-side recovery, combine the reset function with Next.js router capabilities and startTransition from React:

app/blog/error.tsx
"use client";
import { useRouter } from "next/navigation";
import { startTransition } from "react";
export default function ErrorBoundary({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
const router = useRouter();
const reload = () => {
startTransition(() => {
router.refresh();
reset();
});
};
return (
<div>
<h2>Something went wrong!</h2>
<p>{error.message}</p>
<button onClick={reload}>Try again</button>
</div>
);
}

This implementation ensures that the refresh is deferred until the next render phase, allowing React to handle any pending state updates before proceeding.

Testing error recovery

app/blog/page.tsx
export default function BlogPage() {
const random = Math.random();
if (random > 0.5) {
throw new Error("Failed to load blog");
}
return <h1>Blog content loaded successfully</h1>;
}

Now when users encounter the error:

  1. They see the error boundary UI with a retry button
  2. Clicking retry attempts to re-render the component
  3. If the random number is below 0.5, the page loads successfully