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.
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.
Hope it helps and good luck!