Advertisement
Intermediate 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?

Short answer

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…

Save Next.js mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What is the difference between calling notFound and just returning null?
  • Does calling notFound also set the correct HTTP status code?
Related topics