Search code examples
reactjsapinext.jshttp-status-code-404

How to check in Next.js if a dynamic path does not exists and to return 404 after checking in database?


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


Solution

  • 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.