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.tsxhandles any URL that matches no route, and anynotFound()call that is not caught by a closernot-foundfile.- Nested
not-found.tsxfiles (for exampleapp/blog/not-found.tsx) render inside that segment's layouts whennotFound()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-foundcomponents can be async Server Components and fetch data.- Calling
notFound()insidetry/catchswallows it unless you rethrow; useunstable_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
1// app/not-found.tsx2import Link from "next/link";34export 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}1314// app/blog/[slug]/page.tsx15import { notFound } from "next/navigation";16import { getPost } from "@/lib/posts";1718export 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 status2223 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.