Bird
Raised Fist0
NextJSframework~15 mins

Not-found page handling in NextJS - Deep Dive

Choose your learning style10 modes available
Overview - Not-found page handling
What is it?
Not-found page handling in Next.js means showing a special page when a user tries to visit a web address that does not exist on the site. Instead of a confusing error or blank screen, the user sees a clear message that the page was not found. This improves user experience by guiding them back to useful parts of the site. Next.js provides built-in ways to create and show these not-found pages easily.
Why it matters
Without proper not-found page handling, users get lost or frustrated when they visit broken or wrong links. This can make a website look unprofessional and cause visitors to leave. Handling not-found pages helps keep users engaged and improves site navigation. It also helps search engines understand which pages are missing, improving SEO and site health.
Where it fits
Before learning not-found page handling, you should understand basic Next.js routing and pages. After mastering this, you can learn about advanced error handling, custom error pages, and server-side rendering strategies. This topic fits into building robust, user-friendly web applications with Next.js.
Mental Model
Core Idea
A not-found page is a safety net that catches users when they try to visit a missing page and gently guides them back.
Think of it like...
It's like a helpful signpost on a hiking trail that tells you when the path ends and points you back to the main route.
┌───────────────┐
│ User requests │
│ a page URL   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next.js router│
│ checks route  │
└──────┬────────┘
       │
   ┌───┴─────┐
   │ Exists? │
   └───┬─────┘
       │Yes          No
       ▼             ▼
┌───────────────┐  ┌───────────────┐
│ Show page     │  │ Show not-found │
│ component     │  │ page component │
└───────────────┘  └───────────────┘
Build-Up - 7 Steps
1
FoundationBasic Next.js routing concept
🤔
Concept: Learn how Next.js uses the file system to create routes automatically.
In Next.js, every file inside the 'pages' folder becomes a route. For example, 'pages/about.js' becomes '/about'. When a user visits that URL, Next.js shows the corresponding page component.
Result
You can create new pages just by adding files, and users can visit those URLs to see the content.
Understanding file-based routing is key because not-found handling depends on whether a route exists or not.
2
FoundationWhat happens on unknown routes
🤔
Concept: Discover what Next.js does when a user visits a URL that does not match any page.
If a user visits a URL that does not match any file in 'pages', Next.js by default shows a built-in 404 page. This page says 'This page could not be found' with a simple message.
Result
Users see a default 404 page when they visit missing URLs.
Knowing the default behavior helps you decide when and how to customize the not-found page.
3
IntermediateCreating a custom 404 page
🤔Before reading on: do you think you can create a custom 404 page by naming a file '404.js' in the pages folder? Commit to yes or no.
Concept: Learn how to replace the default 404 page with your own design and message.
Next.js lets you create a file named 'pages/404.js'. This file exports a React component that Next.js will show whenever a page is not found. You can style it, add links, or anything you want.
Result
Users see your custom 404 page instead of the default one, improving branding and user experience.
Knowing the special '404.js' filename unlocks easy customization of not-found pages without extra routing logic.
4
IntermediateUsing notFound() in dynamic routes
🤔Before reading on: do you think returning notFound() in getStaticProps triggers the 404 page? Commit to yes or no.
Concept: Learn how to programmatically show the 404 page for dynamic routes when data is missing.
In dynamic routes (like 'pages/posts/[id].js'), you can use getStaticProps or getServerSideProps to fetch data. If the data for a given id does not exist, returning { notFound: true } tells Next.js to show the 404 page instead of the component.
Result
Users see the 404 page when visiting dynamic URLs with missing data, preventing broken pages.
Understanding this lets you control not-found behavior based on data, not just file existence.
5
IntermediateHandling not-found in server components
🤔Before reading on: do you think throwing a special error in a server component can trigger the 404 page? Commit to yes or no.
Concept: Learn how Next.js App Router uses a new method to handle not-found pages in server components.
In Next.js 13+ with the App Router, you can import 'notFound' from 'next/navigation' and call it inside a server component to show the 404 page. This replaces returning { notFound: true } in data functions.
Result
You can trigger the 404 page directly in server components, making handling missing data simpler and more intuitive.
Knowing this new pattern is essential for modern Next.js apps using the App Router.
6
AdvancedCustomizing 404 with layouts and metadata
🤔Before reading on: do you think the 404 page can have its own layout and SEO metadata? Commit to yes or no.
Concept: Learn how to add layouts, titles, and descriptions to your 404 page for better user experience and SEO.
You can wrap your 404 page in a layout component to keep consistent headers or footers. Also, you can add metadata like page title and description to improve SEO and accessibility. This is done by exporting metadata or using Head components.
Result
Your 404 page looks integrated with the rest of the site and helps search engines understand the page purpose.
Customizing metadata on error pages improves professionalism and search engine friendliness.
7
ExpertEdge cases and fallback behaviors
🤔Before reading on: do you think fallback: 'blocking' in getStaticPaths affects 404 page behavior? Commit to yes or no.
Concept: Understand how fallback modes in static generation affect when and how 404 pages appear for dynamic routes.
When using getStaticPaths with fallback: 'blocking' or 'true', Next.js may try to generate pages on demand. If data is missing, returning notFound: true triggers the 404 page. However, fallback: 'false' pre-builds all pages and shows 404 immediately for unknown paths. Knowing these modes helps you control user experience and build times.
Result
You can fine-tune when users see 404 pages and how your app handles missing dynamic content.
Understanding fallback modes prevents unexpected 404s or loading states in production.
Under the Hood
Next.js routing checks the requested URL against the files in the 'pages' or 'app' directory. If no matching route is found, it serves the 404 page. For dynamic routes, data fetching functions can signal missing data by returning a special flag or calling a function, which tells Next.js to render the 404 page instead of the normal content. This happens during server-side rendering or static generation. The 404 page is a React component that Next.js renders with a 404 HTTP status code.
Why designed this way?
Next.js was designed to simplify routing by using the file system, so handling missing pages needed to be automatic and easy to customize. Returning a special flag or calling a function to trigger 404 keeps data fetching and routing logic clean and declarative. This design avoids manual error handling everywhere and integrates well with static and server rendering. Alternatives like manual redirects or error boundaries would be more complex and less consistent.
┌───────────────┐
│ User requests │
│ URL           │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next.js router│
│ matches file? │
└──────┬────────┘
       │No
       ▼
┌───────────────┐
│ Show 404 page │
│ component     │
└───────────────┘

If dynamic route:
┌───────────────┐
│ Fetch data in │
│ getStaticProps│
│ or server comp│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Data missing? │
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Return        │
│ notFound:true │
│ or call       │
│ notFound()    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Show 404 page │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does creating a file named '404.js' automatically fix all not-found errors in dynamic routes? Commit to yes or no.
Common Belief:Many think that just adding a '404.js' page fixes all not-found cases, including dynamic routes with missing data.
Tap to reveal reality
Reality:The custom 404 page only replaces the default page for unknown static routes. For dynamic routes, you must explicitly return notFound: true or call notFound() to trigger the 404 page.
Why it matters:Without this, users may see broken pages or errors instead of the 404 page, harming user experience.
Quick: Does Next.js show the 404 page immediately for all unknown dynamic paths? Commit to yes or no.
Common Belief:Some believe Next.js always shows the 404 page immediately for unknown dynamic routes.
Tap to reveal reality
Reality:If fallback is 'blocking' or 'true', Next.js tries to generate the page on demand and only shows 404 if data is missing after fetching. With fallback 'false', it shows 404 immediately.
Why it matters:Misunderstanding fallback can cause confusion about when users see loading states or 404 pages.
Quick: Can you trigger the 404 page by throwing an error in a React component? Commit to yes or no.
Common Belief:Some think throwing any error inside a component will show the 404 page.
Tap to reveal reality
Reality:Throwing errors usually triggers error boundaries or crashes the app. To show 404, you must return notFound: true or call notFound() explicitly.
Why it matters:Confusing error handling with not-found handling can cause unexpected app crashes or wrong error pages.
Quick: Does the 404 page always return HTTP status 404? Commit to yes or no.
Common Belief:Many assume the 404 page always sends a 404 HTTP status code.
Tap to reveal reality
Reality:Next.js automatically sends a 404 status for the 404 page, but if you render a custom page manually without using notFound or the 404 file, the status might be 200, which misleads browsers and search engines.
Why it matters:Incorrect status codes hurt SEO and can confuse browsers or caching systems.
Expert Zone
1
In Next.js App Router, calling notFound() immediately stops rendering and triggers the 404 page, which differs from returning notFound: true in data functions, showing a shift in control flow.
2
Using fallback: 'blocking' can improve SEO by generating pages on demand but requires careful notFound handling to avoid user confusion or stale content.
3
Custom 404 pages can be enhanced with incremental static regeneration to update content without redeploying, a subtle optimization many miss.
When NOT to use
Not-found page handling is not suitable for handling all errors like server failures or permission issues. Use custom error pages (e.g., 500.js) or error boundaries for those cases. Also, avoid using notFound() for redirects; use redirect() instead.
Production Patterns
In production, teams often combine custom 404 pages with analytics to track broken links. They also use dynamic notFound handling in getStaticProps or server components to gracefully handle missing data. SEO metadata customization on 404 pages is common to maintain site quality.
Connections
HTTP Status Codes
Not-found page handling relies on the 404 HTTP status code to communicate missing resources.
Understanding HTTP status codes helps grasp why 404 pages matter for browsers and search engines.
User Experience Design
Not-found pages are a key part of UX design to keep users informed and engaged when errors occur.
Knowing UX principles guides how to design helpful and friendly 404 pages.
Error Handling in Software Engineering
Not-found page handling is a specialized form of error handling focused on missing resources.
Recognizing this connection helps apply broader error handling best practices to web routing.
Common Pitfalls
#1Assuming the default 404 page is enough for branding and user guidance.
Wrong approach:No 'pages/404.js' file created, relying on Next.js default 404 page.
Correct approach:Create 'pages/404.js' with a custom React component that matches your site's style and provides navigation options.
Root cause:Not realizing the default 404 page is generic and does not help users find their way.
#2Not returning notFound: true in getStaticProps for missing dynamic data.
Wrong approach:export async function getStaticProps(context) { const data = await fetchData(context.params.id); if (!data) { return { props: {} } // missing notFound } return { props: { data } }; }
Correct approach:export async function getStaticProps(context) { const data = await fetchData(context.params.id); if (!data) { return { notFound: true }; } return { props: { data } }; }
Root cause:Misunderstanding how to signal missing data to Next.js for dynamic routes.
#3Throwing errors inside components to trigger 404 page.
Wrong approach:function Page() { if (!data) { throw new Error('Not found'); } return
{data.title}
; }
Correct approach:import { notFound } from 'next/navigation'; function Page() { if (!data) { notFound(); } return
{data.title}
; }
Root cause:Confusing error throwing with the proper Next.js 404 triggering mechanism.
Key Takeaways
Next.js automatically shows a default 404 page for unknown routes, but you can customize it by creating a '404.js' page.
For dynamic routes, you must explicitly tell Next.js to show the 404 page by returning notFound: true or calling notFound() in server components.
Understanding fallback modes in static generation affects when and how 404 pages appear for dynamic content.
Custom 404 pages can and should include layouts and metadata for better user experience and SEO.
Proper not-found handling improves user navigation, site professionalism, and search engine understanding.

Practice

(1/5)
1. What is the purpose of a not-found.tsx file in a Next.js app directory?
easy
A. To display a custom message when a user visits a page that does not exist.
B. To define the main homepage of the website.
C. To handle user authentication and login.
D. To store global CSS styles for the app.

Solution

  1. Step 1: Understand the role of not-found.tsx

    The not-found.tsx file is used to show a special page when a user tries to visit a URL that does not match any existing page.
  2. Step 2: Compare with other options

    The other options describe unrelated features: defining the main homepage, handling user authentication and login, and storing global CSS styles, which are not handled by not-found.tsx.
  3. Final Answer:

    To display a custom message when a user visits a page that does not exist. -> Option A
  4. Quick Check:

    Not-found page = Custom message for missing pages [OK]
Hint: Not-found page shows when URL has no matching page [OK]
Common Mistakes:
  • Confusing not-found.tsx with homepage or layout files
  • Thinking it handles authentication
  • Assuming it manages styles
2. Which of the following is the correct location for the not-found.tsx file in a Next.js 14 app using the App Router?
easy
A. Inside the pages directory
B. Inside the components directory
C. Inside the app directory
D. Inside the public directory

Solution

  1. Step 1: Recall Next.js 14 App Router structure

    In Next.js 14 with the App Router, special files like not-found.tsx belong inside the app directory to define routes and error pages.
  2. Step 2: Eliminate incorrect directories

    The pages directory is for the Pages Router, public is for static assets, and components is for reusable UI parts, not special route files.
  3. Final Answer:

    Inside the app directory -> Option C
  4. Quick Check:

    App Router special files go in app directory [OK]
Hint: App Router files like not-found.tsx go in app folder [OK]
Common Mistakes:
  • Placing not-found.tsx in pages directory (old router)
  • Putting it in public or components folders
  • Confusing app and pages directories
3. Given this not-found.tsx component in Next.js:
export default function NotFound() {
  return (
    <main>
      <h1>Page Not Found</h1>
      <p>Sorry, we couldn't find that page.</p>
    </main>
  )
}

What will a user see if they visit a non-existent page?
medium
A. A blank page with no content
B. The message: 'Page Not Found' and 'Sorry, we couldn't find that page.'
C. An error message from the server
D. The homepage content

Solution

  1. Step 1: Read the JSX returned by NotFound component

    The component returns a main section with a heading 'Page Not Found' and a paragraph apologizing for missing page.
  2. Step 2: Understand Next.js behavior on missing pages

    When a user visits a page that does not exist, Next.js renders this not-found.tsx component, showing the messages inside.
  3. Final Answer:

    The message: 'Page Not Found' and 'Sorry, we couldn't find that page.' -> Option B
  4. Quick Check:

    NotFound component content = shown on missing pages [OK]
Hint: NotFound component content displays on missing pages [OK]
Common Mistakes:
  • Expecting server error instead of custom message
  • Thinking homepage shows instead
  • Assuming blank page appears
4. You wrote a not-found.tsx file but Next.js still shows the default 404 page. What is the most likely mistake?
medium
A. The not-found.tsx file has a syntax error in the JSX.
B. You named the file NotFound.tsx with uppercase letters.
C. You forgot to restart the Next.js development server.
D. The not-found.tsx file is placed inside the components folder instead of app.

Solution

  1. Step 1: Check file placement rules for not-found.tsx

    The not-found.tsx file must be inside the app directory to be recognized by Next.js as the custom 404 page.
  2. Step 2: Analyze other options

    Syntax errors cause build failures, restarting server is good but not required for recognition, and filename is case sensitive but must be exactly not-found.tsx (lowercase). Placing it in components means Next.js ignores it.
  3. Final Answer:

    The not-found.tsx file is placed inside the components folder instead of app. -> Option D
  4. Quick Check:

    File location matters for Next.js to detect not-found page [OK]
Hint: Put not-found.tsx inside app folder, not components [OK]
Common Mistakes:
  • Placing not-found.tsx outside app directory
  • Ignoring case sensitivity of filename
  • Assuming server restart fixes detection
5. You want to create a helpful not-found page in Next.js that includes a link back to the homepage. Which code snippet correctly implements this inside not-found.tsx?
hard
A. export default function NotFound() { return (

Page Not Found

Sorry, we couldn't find that page.

Go back home
) }
B. export default function NotFound() { return (

Page Not Found

Sorry, we couldn't find that page.

Go back home
) }
C. export default function NotFound() { return (

Page Not Found

Sorry, we couldn't find that page.

Go back home
) }
D. export default function NotFound() { return (

Page Not Found

Sorry, we couldn't find that page.

Go back home
) }

Solution

  1. Step 1: Identify correct link usage in Next.js not-found page

    In Next.js, the not-found.tsx page can use a normal <a> tag with href to link back to the homepage. The Link component requires import and is used differently.
  2. Step 2: Check each option's link syntax

    The snippet with <a href="/"> is valid JSX/HTML and requires no imports. Snippets with <Link href="/"> reference undefined Link (missing import { Link } from 'next/link';). Snippets with to="/" use invalid attribute ('to' is for React Router; use href).
  3. Final Answer:

    Using <a href="/">Go back home</a> -> Option A
  4. Quick Check:

    Use <a href="/"> for links in not-found.tsx [OK]
Common Mistakes:
  • Using <Link> without import or proper usage
  • Using 'to' attribute instead of 'href'
  • Forgetting to provide a link back to home
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard