Next.js custom 404 page for slug/dynamic route

Viewed 369

How to set a 404 page in Next.js based on a slug/dynamic route?

My structure:

pages
 ┣ [slug]
 ┃ ┣ 404.js // Custom 404 page for that folder/slug
 ┃ ┣ details.js
 ┃ ┣ index.js
 ┣ _app.js
 ┣ contact.js
 ┣ index.js

Of course I can set a global 404 page, but not for a specific slug. Any ideas?

1 Answers

I do not see any direct way to do it in NextJs docs. But if you are looking to get it done with a little tweaking, you can use router.asPath. You will have the option to change the UI, based on your attempted path

const Custom404 = () => {
  const router = useRouter();
  let attemptedPath = router.asPath;
  if (attemptedPath.startsWith("/folder")) {
    return <div>Custom UI</div>;
  }
  return <div>Usual UI</div>;
};

Edit: Based on your edit, one way to do this can be adding direct checks on all other routes you have. Your if conditions changes like :

const existingRoutes = ['/contact','/','/moreRoutes'];
if (!existingRoutes.includes(attemptedPath)) {
    return <div>Custom UI</div>;
  }

Note: If you have more nested routes then you will have to use both startsWith and complete string equality check. It all depends on your routes.

Related