Redirect to 404 - NextJs 13 App Directory

johndotowl

JohnDotOwl

Posted on September 4, 2023

Redirect to 404 - NextJs 13 App Directory

The next/navigation package introduced in Next.js 13 App Directory makes it easy to handle 404 pages and redirect users when a page is not found.

One way to do this is with the notFound() function. Here's an example:

import { notFound } from 'next/navigation';

export default async function Component({ params }) {
  const { slug } = params;

  const res = await fetch(`https://api.example.com/item/${slug}`);

  if (res.status === 404) {
    notFound();
  }

  const item = await res.json();

  // rest of component
}
Enter fullscreen mode Exit fullscreen mode

This fetches data for an item based on a slug. If the API returns a 404 status, we call notFound().

This will redirect the user to the custom 404 page defined in pages/404.js. It also shows the 404 page UI instantly without waiting for the fetch call, providing a smooth experience.

The key things to note:

notFound() prevents the rest of the component from rendering if called
It shows the 404 page immediately, no loading state
Custom 404 page is defined in src/app/not-found.tsx as usual
Some other examples of when you may want to use notFound():

  • User visits a deleted page
  • Invalid slug parameter
  • Authentication failure

The notFound() function makes handling 404s clean and idiomatic in Next.js. Give it a try in your Next 13 app!

Let me know if you would like me to expand on any part of this post. I'm happy to include more details on how to customize the 404 page, integrate with an CMS, or any other use cases!

💖 💪 🙅 🚩
johndotowl
JohnDotOwl

Posted on September 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related