Next.js Error Handling details how to catch runtime component exceptions, display fallback error screens, and handle 404 missing resource pages gracefully.
Adding an error.tsx file inside any route segment automatically wraps child components in a React Error Boundary.
error.tsx)Error boundaries must be declared as Client Components ('use client'). They receive the error object and a reset() method to retry rendering:
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Log exception to logging services like Sentry or Datadog
console.error('Logged runtime exception:', error);
}, [error]);
return (
<div className="p-6 bg-red-50 rounded-lg border border-red-200 text-center">
<h2 className="text-xl font-bold text-red-800">Something went wrong!</h2>
<p className="mt-2 text-sm text-red-600">{error.message}</p>
<button
onClick={() => reset()}
className="mt-4 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
>
Try Again
</button>
</div>
);
}
not-found.tsx)Create a not-found.tsx file inside any route folder to present clean 404 screens when requested resources do not exist:
// app/not-found.tsx
import Link from 'next/link';
export default function NotFound() {
return (
<div className="flex flex-col items-center justify-center min-h-[60vh]">
<h2 className="text-4xl font-bold text-gray-800">404 - Page Not Found</h2>
<p className="mt-2 text-gray-600">The page or resource you requested could not be located.</p>
<Link href="/" className="mt-6 px-4 py-2 bg-blue-600 text-white rounded">
Return Home
</Link>
</div>
);
}
Use the notFound() utility function inside Server Components or Route Handlers to trigger 404 state explicitly:
// app/posts/[id]/page.tsx
import { notFound } from 'next/navigation';
export default async function PostPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const res = await fetch(`https://api.example.com/posts/${id}`);
if (!res.ok) {
notFound(); // Renders nearest not-found.tsx component
}
const post = await res.json();
return <article><h1>{post.title}</h1></article>;
}
reset() button inside error UI components to allow users to attempt recovery without reloading the application.error.digest property in tracking tools for backend error correlation.Next.js handles runtime errors and missing resources with declarative boundary components. error.tsx catches UI failures gracefully while not-found.tsx delivers clean 404 user experiences.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With