Next SSR Error Boundary Recovery

Contain server rendering failures in Next.js with route-level error boundaries, distinguishing retryable render errors from hard failures.

TypescriptNextResilience

Code

typescriptsnippet
44 lines
// serverSide rendering error boundary recovery
// app/dashboard/error.tsx — 路由级错误边界(客户端组件)
'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';

interface DashboardErrorProps {
  error: Error & { digest?: string };
  reset: () => void;
}

export default function DashboardError({ error, reset }: DashboardErrorProps) {
  const router = useRouter();
  const isRetryable = !error.message.includes('authorization');

  useEffect(() => {
    // digest 由服务端生成,用于在日志中精确定位本次渲染失败
    console.error('dashboard render failed:', error.digest, error.message);
  }, [error]);

  if (!isRetryable) {
    return (
      <section role="alert">
        <h2>Access denied</h2>
        <button onClick={() => router.push('/login')}>Go to login</button>
      </section>
    );
  }

  return (
    <section role="alert">
      <h2>Dashboard failed to render</h2>
      <p>This section hit a transient error. Other page areas still work.</p>
      <button onClick={() => reset()}>Retry this section</button>
    </section>
  );
}

// 服务端组件抛错示例:
// export default async function Page() {
//   const stats = await fetchStats(); // 抛错时仅该段被边界捕获
//   return <StatsCard stats={stats} />;
// }

What the code does

The whole file is the DashboardError client component: it splits retryable from fatal via error.message.includes('authorization'), logs the server-generated error.digest through useEffect, and returns either a login redirect or a reset() button.

The import line is the dependency contract: useEffect, useRouter come from react and nothing else.

Points of care

  • Requires react and next/navigation as packages; the snippet will not run without them.
  • The guard !isRetryable short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads export default function DashboardError({ error, reset }: DashboardErrorProps)

The only direct print is the useEffect log — dashboard render failed: followed by the digest and the error message — which is how one failed server render gets pinned to a log entry.

Import DashboardError from the file and call it — the rest of the code is implementation detail.

Statements that matter

<button onClick={() => router.push('/login')}>Go to login</button>
</section>
);
<button onClick={() => reset()}>Retry this section</button>
</section>
);
reset: () => void;

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `react` and `next/navigation`. Add them to your project before running the snippet.