Search code examples
http-status-code-404next.js13

Unhandled Runtime Error Error: notFound() is not allowed to use in root layout


Getting the error Unhandled Runtime Error Error: notFound() is not allowed to use in root layout

next js 13 with app directory (v 13.4.12)

Importing notFound :

import { notFound } from 'next/navigation'

Then using it in my function, which when the user does enter a route that is not vaild or returned it goes to 404.

  // Throw 404 if user requests invalid project
  if (!project) {
    return notFound();
  }

However the error: Unhandled Runtime Error Error: notFound() is not allowed to use in root layout occurs.

Anyone having the same issue with this?


Solution

  • According to docs:

    Invoking the notFound() function throws a NEXT_NOT_FOUND error and terminates rendering of the route segment in which it was thrown. Specifying a not-found file allows you to gracefully handle such errors by rendering a Not Found UI within the segment.

    So you need to create a not-found.js file in your page's or it's parent directories (if you want it to be shared by other children pages)

    //not-found.js
    import Link from 'next/link'
     
    export default function NotFound() {
      return (
        <div>
          <h2>Not Found</h2>
          <p>Could not find requested resource</p>
          <Link href="/">Return Home</Link>
        </div>
      )
    }