Next.js › Error Handling & Not Found Pages
How would you manually trigger a not found response when a specific piece of data, like a product, does not exist?
IntermediateAnswer
You call the notFound function imported from next/navigation inside your page or data fetching logic whenever the requested data cannot be found, which immediately stops rendering the current page and shows the closest not-found.js file instead, giving users an accurate 404 experience.
import { notFound } from 'next/navigation';
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await getProduct(id);
if (!product) {
notFound();
}
return <h1>{product.name}</h1>;
}Real-world example A product page checks if the requested product id actually exists in the database, and shows the proper 404 page immediately if a customer tries to visit a product that has been removed.