Using the Not Found page in NextJs

One of the special pages in NextJs for the app folder is not-found.js, or not-found.tsx.

As the name implies it is used for cases when we want to signal that a specific item was not found. It just renders a basic React component:

// app/products/not-found.js
export default function NotFound() {
    return <h3>
        "🚫 Item was not found ..."
    </h3>
}

How to show the not found file in NextJs

We can invoke the not found file by simply calling the notFound() function:

// app/products/page.js
import { notFound } from 'next/navigation'

export default function ProductsPage() {
    if (condition) {
        //will render not-found.js instead if app.js
        notFound()
    }
    // rest of the page here
}

So, if we add the query params we can have:

// app/products/[id]/page.js
import { notFound } from 'next/navigation'

export default function ProductsPage({ params }) {
    if (params.id = 123) {
        notFound()
    }
    // rest of the page here
}

And if we go to http://localhost:3000/products/123 we will see the not found page:
screenshot of a not found page in NextJs

Please note that this page does not accept any parameters.

Also, the not found page will add the <meta name="robots" content="noindex" /> meta tag to the page.

As a closing note, if NextJs will not find the not-found.js in the same folder as the page that invoked notFound() then it will look in the parent folder, and so on.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X