Bird
Raised Fist0
NextJSframework~15 mins

Not-found.tsx customization in NextJS - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - not-found.tsx Customization
What is it?
In Next.js, not-found.tsx Customization means changing the default page that shows when a user visits a URL that does not exist. This page is called the 404 page. By customizing it, you can create a friendly message or helpful links instead of a plain error. It helps users stay on your site even when they make a mistake in the address.
Why it matters
Without customizing the 404 page, users see a generic error that can be confusing or frustrating. This can make them leave your site quickly. A customized 404 page improves user experience by guiding visitors back to useful content, reducing lost visitors and improving your site's professionalism and trust.
Where it fits
Before customizing not-found.tsx, you should understand basic Next.js routing and React components. After this, you can learn about dynamic routing and error handling in Next.js to build more robust applications.
Mental Model
Core Idea
The not-found.tsx page is a special React component that Next.js shows automatically when no matching route is found, and customizing it means replacing that default with your own friendly message or design.
Think of it like...
It's like having a helpful receptionist in a building who guides lost visitors instead of just saying 'No entry'.
┌───────────────┐
│ User visits   │
│ a URL         │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next.js checks│
│ routes        │
└──────┬────────┘
       │
   Route found? ──No──▶ Show not-found.tsx (custom 404 page)
       │Yes
       ▼
┌───────────────┐
│ Show page     │
│ component     │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is not-found.tsx in Next.js
🤔
Concept: Introducing the special 404 page component in Next.js called not-found.tsx.
Next.js automatically shows a default 404 page when a user visits a URL that does not match any page in your app. You can create a file named 'not-found.tsx' inside the 'app' directory to replace this default page with your own design and message.
Result
When a user visits a missing page, Next.js shows your custom not-found.tsx page instead of the default error.
Understanding that not-found.tsx is just a React component Next.js uses for missing pages helps you realize you can fully control what users see on errors.
2
FoundationBasic not-found.tsx Component Structure
🤔
Concept: How to write a simple not-found.tsx component using React in Next.js.
Create a file 'app/not-found.tsx' with a React function that returns JSX. For example: export default function NotFound() { return

Page Not Found

; } This component will be rendered automatically for 404 errors.
Result
Your app now shows 'Page Not Found' text on missing pages instead of the default message.
Knowing that not-found.tsx is a React component means you can use all React features to customize the 404 page.
3
IntermediateAdding Navigation to not-found.tsx
🤔Before reading on: Do you think adding a link back to home on the 404 page improves user experience? Commit to yes or no.
Concept: Enhancing the not-found.tsx page by adding links or buttons to guide users back to working pages.
You can import Next.js Link component and add a link to the homepage: import Link from 'next/link'; export default function NotFound() { return (

Page Not Found

Sorry, we couldn't find that page.

Go back home
); } This helps users recover from errors.
Result
Users see a friendly message with a clickable link to return home on 404 pages.
Understanding that guiding users back reduces frustration and keeps them engaged improves your site's usability.
4
IntermediateStyling not-found.tsx for Better UX
🤔Before reading on: Do you think styling the 404 page with colors and layout affects user perception? Commit to yes or no.
Concept: Applying CSS or Tailwind styles to make the not-found.tsx page visually appealing and consistent with your site.
You can add styles inline, with CSS modules, or Tailwind. Example with Tailwind: import Link from 'next/link'; export default function NotFound() { return (

404

Oops! Page not found.

Return Home
); } This creates a centered, clear message with a styled link.
Result
The 404 page looks professional and matches your site's style, improving trust.
Knowing that good design on error pages influences user trust and reduces bounce rates is key for real-world apps.
5
IntermediateUsing Dynamic Content in not-found.tsx
🤔Before reading on: Can the 404 page show different messages based on user data or time? Commit to yes or no.
Concept: Incorporating dynamic React features like state or effects to customize the 404 page content dynamically.
"use client"; import { useState, useEffect } from 'react'; const messages = [ "Oops! Lost your way?", "This page took a day off.", "Nothing to see here, move along!" ]; export default function NotFound() { const [msg, setMsg] = useState(''); useEffect(() => { const random = messages[Math.floor(Math.random() * messages.length)]; setMsg(random); }, []); return

{msg}

; } This makes the page feel more friendly and less repetitive.
Result
Users see different messages each time they hit a 404, making the experience more engaging.
Understanding that not-found.tsx is a full React component lets you use all React features to improve user experience.
6
AdvancedHandling not-found.tsx with Server Components
🤔Before reading on: Do you think not-found.tsx can be a server component in Next.js 13+? Commit to yes or no.
Concept: Using Next.js 13+ app directory features, not-found.tsx can be a server component to fetch data or handle logic before rendering.
By default, not-found.tsx is a React Server Component. You can fetch data or check conditions before showing the 404 message: export default async function NotFound() { // Example: fetch some data or log // await fetch('/api/log404'); return

Page Not Found

; } This allows you to integrate analytics or customize content based on server data.
Result
Your 404 page can perform server-side logic, improving monitoring or personalization.
Knowing that not-found.tsx runs on the server lets you add powerful features without client overhead.
7
ExpertCustomizing not-found.tsx with Middleware and Redirects
🤔Before reading on: Can middleware be used to redirect users before not-found.tsx shows? Commit to yes or no.
Concept: Using Next.js middleware to intercept requests and redirect or rewrite URLs before the 404 page appears, enhancing control over missing routes.
// middleware.ts import { NextResponse } from 'next/server'; export function middleware(request) { const url = request.nextUrl.clone(); if (url.pathname === '/old-path') { url.pathname = '/new-path'; return NextResponse.redirect(url); } return NextResponse.next(); } This can prevent some 404s by redirecting outdated URLs, reducing not-found.tsx triggers.
Result
Users get redirected smoothly from old or wrong URLs, improving site navigation and reducing error pages.
Understanding middleware's role before not-found.tsx lets you build smarter routing and better user experiences.
Under the Hood
Next.js uses its routing system to match the requested URL to files in the 'app' or 'pages' directory. If no match is found, it automatically renders the not-found.tsx component if present. This component is treated as a React Server Component in the app directory, meaning it runs on the server to generate HTML before sending it to the browser. This allows for fast, SEO-friendly error pages that can include server-side logic.
Why designed this way?
Next.js aims to provide a seamless developer experience with automatic routing and error handling. By using a special not-found.tsx file, developers can easily customize 404 pages without extra configuration. Making it a server component fits the modern React and Next.js architecture, enabling better performance and flexibility. Alternatives like manual error handling would be more complex and error-prone.
┌───────────────┐
│ User requests │
│ URL           │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next.js Router│
│ matches path? │
└──────┬────────┘
       │No
       ▼
┌───────────────┐
│ Render        │
│ not-found.tsx │
│ component     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Server sends  │
│ 404 page HTML │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does creating a '404.tsx' file customize the 404 page in Next.js app directory? Commit yes or no.
Common Belief:Many believe that naming the file '404.tsx' customizes the 404 page in the app directory.
Tap to reveal reality
Reality:In Next.js app directory, the correct file name is 'not-found.tsx' (all lowercase, no numbers). '404.tsx' is ignored for 404 customization.
Why it matters:Using the wrong file name means your custom page won't show, and users see the default error, hurting user experience.
Quick: Does not-found.tsx only work in the app directory, not in pages? Commit yes or no.
Common Belief:Some think not-found.tsx customization works the same in both 'pages' and 'app' directories.
Tap to reveal reality
Reality:not-found.tsx is specific to the app directory in Next.js 13+. The pages directory uses '404.js' or '404.tsx' instead.
Why it matters:Confusing these leads to customization not working and wasted debugging time.
Quick: Can not-found.tsx fetch client-side data like normal React components? Commit yes or no.
Common Belief:People often believe not-found.tsx can fetch data on the client side like typical React components.
Tap to reveal reality
Reality:not-found.tsx is a server component by default and cannot use client-side hooks like useEffect for fetching data unless marked as a client component.
Why it matters:Trying to use client hooks causes errors or no data loading, breaking the 404 page.
Quick: Does middleware run after not-found.tsx renders? Commit yes or no.
Common Belief:Some think middleware runs after the 404 page is shown to the user.
Tap to reveal reality
Reality:Middleware runs before routing and rendering, so it can redirect or rewrite requests before not-found.tsx is triggered.
Why it matters:Misunderstanding this order can cause incorrect routing logic and unexpected 404 pages.
Expert Zone
1
not-found.tsx can be combined with error.tsx to handle different error types separately, improving error management.
2
Because not-found.tsx is a server component, you can integrate it with server-side analytics or logging without client overhead.
3
Middleware can be used to preemptively redirect or rewrite URLs, reducing the number of 404s and improving SEO.
When NOT to use
not-found.tsx customization is not suitable if you need client-side interactivity or animations on the 404 page; in such cases, use client components inside not-found.tsx or fallback to pages directory 404.js for client-side control. Also, if you want global error handling beyond 404s, consider using error.tsx or middleware instead.
Production Patterns
In production, teams often customize not-found.tsx with branded messages, search bars, and navigation links to keep users engaged. They also integrate server-side logging inside not-found.tsx to track missing URLs. Middleware is used to redirect deprecated URLs to new ones, minimizing 404 hits. Some use dynamic content in not-found.tsx to personalize messages based on user location or time.
Connections
Error Handling in Web Servers
not-found.tsx is a specialized form of error handling for missing pages, similar to HTTP 404 responses in web servers.
Understanding how web servers handle 404 errors helps grasp why customizing not-found.tsx improves user experience and SEO.
React Server Components
not-found.tsx is a React Server Component in Next.js app directory, sharing the same rendering model and lifecycle.
Knowing React Server Components clarifies how not-found.tsx can fetch data and render on the server before sending HTML.
Customer Service Reception
Both not-found.tsx and a receptionist guide lost visitors to the right place, preventing frustration.
Recognizing this connection highlights the importance of friendly error pages in digital user experience.
Common Pitfalls
#1Using wrong file name for 404 customization.
Wrong approach:Creating '404.tsx' inside 'app' directory expecting it to customize 404 page.
Correct approach:Create 'not-found.tsx' inside 'app' directory for 404 customization.
Root cause:Confusing legacy pages directory naming with new app directory conventions.
#2Trying to use client-side hooks in not-found.tsx.
Wrong approach:Using useEffect or useState in not-found.tsx without marking it as a client component. export default function NotFound() { useEffect(() => { console.log('Hello'); }); return

Page Not Found

; }
Correct approach:"use client"; import { useEffect } from 'react'; export default function NotFound() { useEffect(() => { console.log('Hello'); }); return

Page Not Found

; }
Root cause:not-found.tsx is server component by default; client hooks require explicit client directive.
#3Expecting middleware to run after not-found.tsx renders.
Wrong approach:// middleware.ts export function middleware(request) { // code expecting to run after 404 page return NextResponse.next(); }
Correct approach:// middleware.ts export function middleware(request) { if (request.nextUrl.pathname === '/old') { return NextResponse.redirect(new URL('/', request.url)); } return NextResponse.next(); }
Root cause:Misunderstanding middleware runs before routing and rendering.
Key Takeaways
not-found.tsx is the special React component Next.js uses to show custom 404 pages in the app directory.
Customizing not-found.tsx improves user experience by providing friendly messages and navigation on missing pages.
not-found.tsx is a React Server Component, so it runs on the server and can include server-side logic.
Middleware runs before not-found.tsx and can redirect or rewrite URLs to reduce 404 errors.
Using the correct file name and understanding server vs client components is essential for successful customization.

Practice

(1/5)
1. What is the main purpose of the not-found.tsx file in a Next.js app?
easy
A. To define the main layout of the website
B. To handle user authentication
C. To customize the page shown when a user visits a missing URL
D. To manage API routes

Solution

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

    This file is specifically for customizing the page shown when a user tries to access a page that does not exist.
  2. Step 2: Compare with other options

    Other options like layout, authentication, or API routes are handled by different files or folders in Next.js.
  3. Final Answer:

    To customize the page shown when a user visits a missing URL -> Option C
  4. Quick Check:

    Missing page display = Custom not-found.tsx [OK]
Hint: Remember: not-found.tsx shows missing page content [OK]
Common Mistakes:
  • Confusing not-found.tsx with layout or API files
  • Thinking it handles authentication
  • Assuming it manages site navigation
2. Which of the following is the correct way to export a default React component in not-found.tsx?
easy
A. default export function NotFound() { return

Page Not Found

; }
B. function NotFound() { return

Page Not Found

; } export NotFound;
C. export function NotFound() { return

Page Not Found

; }
D. export default function NotFound() { return

Page Not Found

; }

Solution

  1. Step 1: Recall correct default export syntax

    In React with Next.js, the correct way is to write export default function ComponentName() { ... }.
  2. Step 2: Check each option

    export default function NotFound() { return

    Page Not Found

    ; } matches the correct syntax. function NotFound() { return

    Page Not Found

    ; } export NotFound; has incorrect export syntax. export function NotFound() { return

    Page Not Found

    ; } exports a named function, not default. default export function NotFound() { return

    Page Not Found

    ; } uses invalid syntax.
  3. Final Answer:

    export default function NotFound() { return <h1>Page Not Found</h1>; } -> Option D
  4. Quick Check:

    Default export = export default function [OK]
Hint: Default export uses 'export default function' syntax [OK]
Common Mistakes:
  • Using named export instead of default
  • Incorrect export keyword placement
  • Missing 'default' keyword
3. Given this not-found.tsx component, what will be displayed when a user visits a missing page?
export default function NotFound() {
  return (
    <main role="main">
      <h1>Oops! Page not found.</h1>
      <p>Try going back or visit the homepage.</p>
      <a href="/">Home</a>
    </main>
  );
}
medium
A. A page with a heading 'Oops! Page not found.', a paragraph, and a link to Home
B. A blank page with no content
C. An error message in the browser console only
D. A redirect to the homepage without showing any message

Solution

  1. Step 1: Read the returned JSX

    The component returns a main section with a heading, paragraph, and a link to the homepage.
  2. Step 2: Understand what renders on missing page

    When a page is missing, this component renders the content exactly as coded, showing the heading, paragraph, and link.
  3. Final Answer:

    A page with a heading 'Oops! Page not found.', a paragraph, and a link to Home -> Option A
  4. Quick Check:

    JSX content renders as visible page elements [OK]
Hint: JSX inside return shows on missing page [OK]
Common Mistakes:
  • Thinking it redirects automatically
  • Assuming no content shows
  • Confusing console errors with UI output
4. Identify the error in this not-found.tsx code snippet:
export default function NotFound() {
  return (
    <div>
      <h1>Page Not Found</h1>
      <a href="/">Go Home</a>
    </div>
  )
}
medium
A. Using <div> instead of <main> for accessibility
B. No error; code is valid and works correctly
C. Missing semicolon after return statement
D. Missing parentheses around JSX

Solution

  1. Step 1: Check JSX syntax

    The JSX is correctly wrapped and returned; no syntax errors or missing semicolons needed after return.
  2. Step 2: Consider accessibility best practices

    Using <main> instead of <div> improves accessibility by defining the main content region.
  3. Final Answer:

    Using <div> instead of <main> for accessibility -> Option A
  4. Quick Check:

    Use <main> for main content in error pages [OK]
Hint: Use <main> tag for main content, not just <div> [OK]
Common Mistakes:
  • Thinking semicolons are required after return
  • Ignoring accessibility tags
  • Assuming JSX needs extra parentheses
5. You want your not-found.tsx page to show a custom message only if the user is on a mobile device, otherwise show a default message. Which approach fits Next.js best?
hard
A. Create two separate not-found.tsx files, one for mobile and one for desktop
B. Use a React hook like useEffect with window.navigator.userAgent to detect device and conditionally render
C. Use CSS media queries to hide/show different messages in the same component
D. Write server-side code in not-found.tsx to detect device from request headers and render accordingly

Solution

  1. Step 1: Understand client vs server rendering

    Device detection using window.navigator.userAgent works only on client side, so use React hooks like useEffect.
  2. Step 2: Evaluate other options

    Server-side detection is complex and not typical in not-found.tsx. CSS media queries only style but don't change content. Multiple files for one route is invalid.
  3. Final Answer:

    Use a React hook like useEffect with window.navigator.userAgent to detect device and conditionally render -> Option B
  4. Quick Check:

    Client detection with hooks = best for device-specific UI [OK]
Hint: Detect device client-side with hooks, not server or multiple files [OK]
Common Mistakes:
  • Trying to detect device server-side in this file
  • Using multiple not-found.tsx files
  • Relying only on CSS for content changes