404 Handling

15-30 minBeginner

Implement custom 404 error pages in Next.js using the file-system based router.

Prerequisites

  • Next.js 13+ App Router project
  • Understanding of React components
Beginner Recommended

App Router (Next.js 13+)

Using `not-found.tsx` file.

1

Create not-found.tsx

1

Create a not-found.tsx file in your app directory.

2

Default path: src/app/not-found.tsx.

Example
import Link from 'next/link'

export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}
2

Triggering 404s

1

Import the notFound function from next/navigation.

2

Call it within a page or route handler when a resource doesn't exist.

Example
import { notFound } from 'next/navigation'

export default async function Profile({ params }: { params: { id: string } }) {
  const user = await fetchUser(params.id)

  if (!user) {
    notFound()
  }

  return <div>...</div>
}

Verification Checklist

  • Visit a non-existent URL (e.g., /random-page) and verify your custom 404 UI renders.
  • Check that the HTTP status code returned is 404 using DevTools Network tab.