Recovering from Server Errors
Explore how to implement a robust recovery mechanism for server errors in Next.js applications. Understand the limitations of simple resets, learn to refresh server state using router.refresh(), and synchronize retries with React's useTransition to avoid stale data and ensure smooth user experience.
Early on in the course, we introduced error.js to show a fallback UI. However, we deferred a critical problem: how to actually recover. Now that we understand useTransition, we can build a proper recovery mechanism.
Triggering a failure in a Server Component
To test our recovery mechanism, we’ll use a simple Server Component that simulates an intermittent system failure during rendering. This action is designed to fail 50% of the time, allowing us to test our recovery sequence interactively.
// app/dashboard/page.js// Force dynamic rendering so the error chance is re-evaluated on every requestexport const dynamic = 'force-dynamic';export default async function Dashboard() {// Simulate a 50% chance of an unexpected system failureif (Math.random() > 0.5) {throw new Error('Temporary connection loss. Please retry.');}// Success path (returns data for the consuming component)return (<div style={{ color: 'green', fontWeight: 'bold' }}>Data processed successfully!</div>);}
When the user visits this page and the error is thrown, the entire segment is replaced by our error.js fallback UI.
Recap: React error boundary
Recall that the error.js component automatically wraps a route segment, providing a fallback UI when runtime errors occur within that segment. It is always a Client Component and receives two primary props: