Home > Software engineering >  How to check in Next.js if a dynamic path does not exists and to return 404 after checking in databa
How to check in Next.js if a dynamic path does not exists and to return 404 after checking in databa

Time:03-03

For example localhost:3000/categories/1 exists, but localhost:3000/categories/2 does not exists so to return 404 that page does not exists

pages
|
----categories
-----------index.js
-----------[id].js

For example if an ID does not exist in the database, how to pre-check if does not exists return 404 page

CodePudding user response:

I would fetch for data on your front-end, if data exists display the page if not redirect to your 404 error page.

CodePudding user response:

At the getServerSideProps check for the data, and if data does not exists:

  if (!categories) {
    return {
      notFound: true,
    };
  }

This will return to the 404 file.

  • Related