šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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 *