Next.js 13.3: Automatic Handling of Unmatched Routes with not-found.js
Introduction
In the fast-paced world of web development, Next.js continues to evolve and improve. With the release of Next.js 13.3, a new feature has been introduced that simplifies how you handle unmatched routes in your application. This feature makes it even more developer-friendly and streamlines the process of creating a custom 404 page. In this blog post, we'll explore these changes and how you can take advantage of them.
callout
🚀 Let’s build something great together. 💡
Email: heyshabink@gmail.com
The Not-Found Page in Next.js
With Next.js 13.3, managing custom 404 pages and handling unmatched routes has become remarkably more straightforward. All you need to do is change the file name to not-found.js
. An app/not-found.js
file will now automatically handle visits to a URL that does not have a matching route in your app.
You can find detailed information about this file convention in the Next.js documentation.
This exciting update was officially announced in the Next.js 13.3 release notes.
Important Note: While Next.js 13.3 simplifies the process of handling unmatched routes, there's a crucial detail to be aware of. The
not-found.js
file currently only renders when triggered by thenotFound
function. However, the Next.js team is actively working on adding support for automatically catching unmatched routes, making it even more seamless. To take advantage of the current functionality, ensure that your custom 404 page is namednot-found.js
instead of404.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.
Here's how you can do it:
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>
}
Please note that this approach can potentially create problems if you have multiple dynamic routes in your app folder. However, if you have dynamic routes in another static folder, you should be able to use this approach without issues.
Happy coding with Next.js!
Top comments (4)
thaaaaankyoooo @shabink
How it do in next 14, and with locale? For expample
But it doesn't work
I guess you have already found the solution, but for anyone who face the same problem - the secret is here: next-intl-docs.vercel.app/docs/env...
You need to manually create the page to catch all the unknown routes and trigger 404 error. This way it works with next-intl.
Thanks