Picture
Arshad Senior Developer
October 30, 2022

Next.js 13 uses special files for routing. Example route-name/page.tsx for building UI and route-name/loading.tsx for loading components.

For page not found/404 errors, we use a special route-name/not-found.tsx file.


Custom 404 page

Let’s start by adding a custom 404 page for handling post not found errors.

Create a file at app/posts/[...slug]/not-found.tsx

Here’s what the file structure would look like:

not-found.tsx

We can now add some code to show custom components for 404 errors:


// app/posts/[...slug]/not-found.tsx
export default function PostNotFound() {
  return <p>Uh oh! This post could not be found.</p>
}


Throwing 404 errors

To show our custom 404 page, we call notFound() in app/posts/[...slug]/page.tsx:

// app/posts/[...slug]/page.tsx
import { notFound } from "next/navigation"

function getPostBySlug(slug) {
  // ...
}

export default async function PostPage({ params }) {
  const post = await getPostBySlug(params.slug)

  if (!post) {
    notFound()	
  }

  return <Post post={post} />
}


Notes:

  1. Do not return notFound(). notFound does not return a component. It just throws a NEXT_NOT_FOUND error.
  2. not-found.tsx is for 404 errors. For other error types, see error.tsx