When a user tries to access a page that doesn't exist, it's good to show a 404 page (along with a 404 HTTP status code).
With Next.js' App Router you can accomplish this by returning notFound()
from the next/navigation
module in page.{js,tsx}
.
app/[slug]/page.tsx
import { notFound } from 'next/navigation'async function BlogPostPage({ params }) {const blogPost = await fetchBlogPost({ slug: params.slug })if (!blogPost) {return notFound()}return <BlogPost blogPost={blogPost} />}export default BlogPostPage
By default, the 404 page looks something like this:
How to Customize the Next.js 404 Page
If you don't like the style of Next.js' default 404 page, you can customize its look with the not-found.{js,tsx}
file.
Example:
app/not-found.tsx
function NotFoundPage() {return <h1>Page not found</h1>}export default NotFoundPage
Find out more by visiting the Next.js docs.