Thursday, 12 January, 2023 UTC


Summary

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:
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.
The post Using the Not Found page in NextJs appeared first on Js Craft.