Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not-found page does not work in Next.js 13

This is the structure of my Next.js project:

enter image description here

And my 404.js page is :

'use client';

export default function NotFound() {
    return (
        <div>
            <h2>Not Found</h2>
        </div>
    );
}

When I enter a wrong route it does not work and does not go to my custom page and goes to next.js 404 page. Why? Where am I wrong?

like image 204
Ghasem Khalili Avatar asked Sep 12 '25 14:09

Ghasem Khalili


1 Answers

With Next 13.3 you just need to change the file name to not-found.js.

An app/not-found.js file will now automatically handle visits to an URL that does not have a matching route in your app.

Docs: https://nextjs.org/docs/app/api-reference/file-conventions/not-found

Announced in : https://nextjs.org/blog/next-13-3


With Next 13.2, according to the docs:

"Note: not-found.js currently only renders when triggered by the notFound function, we're working on support for catching unmatched routes."

So it's not yet automatic but looks like they are working on it. File should also be named not-found.js instead of 404.js,

In the meantime, as it looks like dynamic routes are resolved after static routes, you can solve it by creating a dynamic catch-all route using a [...not_found] folder and add it to your app folder.

Image of folder structure for a Next 13 application showing the app folder with a [...not_found] folder, an articles folder and a layout.js, not-found.js, and page.js file in the root of the app folder.

Inside the dynamic route folder add a page.js file that calls the notFound() function.

app/[...not_found]/page.js

import {notFound} from "next/navigation"

export default function NotFoundCatchAll() {
  notFound()
}

And inside the not-found.js file in the root of your app folder you can add your custom 404 page.

app/not-found.js

import Link from 'next/link'

export default function NotFound() {
  return <div>
      <h1>Not found – 404!</h1>
      <div>
        <Link href="/">Go back to Home</Link>
      </div>
  </div>
}

Important to note that this approach can create problems if you have multiple dynamic routes in your app folder. Dynamic routes in another static folder should be fine however.

like image 152
Fredrik Carlsson Avatar answered Sep 16 '25 07:09

Fredrik Carlsson