Topic 17 of 39
Not Found UI
Overview
The not-found.tsx file allows you to create custom 404 pages for specific route segments. It is triggered automatically when an invalid URL is visited, or manually when you call the notFound() function in a component.
Syntax
tsx
// app/not-found.tsx (Global 404)
import Link from 'next/link';
export default function NotFound() {
return (
<div className="text-center mt-20">
<h2 className="text-4xl font-bold">404 - Not Found</h2>
<p>Could not find requested resource</p>
<Link href="/" className="text-blue-500 hover:underline">
Return Home
</Link>
</div>
);
}Common Pitfalls
- Not providing a global
app/not-found.tsx(Next.js provides a default, but it's plain). - Forgetting to import
notFoundfromnext/navigationwhen manually triggering a 404 state for missing data.
Interview Questions
Q:
How do you programmatically trigger a 404 page if a database query returns null?
A:
You import the notFound() function from next/navigation and call it. This throws a special error that Next.js catches and renders the nearest not-found.tsx file.
Real-World Example
Triggering a 404 when a product ID doesn't exist.
example
tsx
import { notFound } from 'next/navigation';
import db from '@/lib/db';
export default async function ProductDetails({ params }) {
const product = await db.product.findById(params.id);
if (!product) {
notFound(); // Stops execution and renders not-found.tsx
}
return <div>{product.name}</div>;
}Check Your Knowledge
Test your understanding of Not Found UI with these quick questions.