Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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.

Home Screencasts Best of Newsletter Search X