How do you create a 404 page in Next.js?

In the App Router, create app/not-found.tsx for unmatched URLs and call notFound() from next/navigation when a resource does not exist. In the Pages Router, create pages/404.tsx.

App Router

  • app/not-found.tsx handles any URL that matches no route, and any notFound() call that is not caught by a closer not-found file.
  • Nested not-found.tsx files (for example app/blog/not-found.tsx) render inside that segment's layouts when notFound() is called there.
  • notFound() throws a special error that stops rendering and returns a 404 status (when called before streaming starts). It also adds <meta name="robots" content="noindex">.
  • not-found components can be async Server Components and fetch data.
  • Calling notFound() inside try/catch swallows it unless you rethrow; use unstable_rethrow(err) in the catch block.

Global not-found

For apps with several root layouts (for example per route group), app/global-not-found.tsx renders a complete document for unmatched URLs. It requires the experimental.globalNotFound flag and must render its own <html> and <body>.

Pages Router

pages/404.tsx is statically generated at build time. Return { notFound: true } from getStaticProps or getServerSideProps to render it for missing data.

Interview point

A 404 page should be helpful (search, links home) and must return a real 404 status so search engines drop the URL. A "soft 404" with a 200 status hurts SEO.

Code example

tsx
1// app/not-found.tsx
2import Link from "next/link";
3
4export default function NotFound() {
5 return (
6 <main>
7 <h1>Page not found</h1>
8 <p>The page you are looking for does not exist.</p>
9 <Link href="/">Go home</Link>
10 </main>
11 );
12}
13
14// app/blog/[slug]/page.tsx
15import { notFound } from "next/navigation";
16import { getPost } from "@/lib/posts";
17
18export default async function Post({ params }: PageProps<"/blog/[slug]">) {
19 const { slug } = await params;
20 const post = await getPost(slug);
21 if (!post) notFound(); // renders the nearest not-found.tsx with a 404 status
22
23 return <h1>{post.title}</h1>;
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app