'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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1