Home > Back-end >  NextJs how am I supposed to handle 404 errors in client side fetched dynamic routes?
NextJs how am I supposed to handle 404 errors in client side fetched dynamic routes?

Time:08-29

So I have the a dynamic route lets say it is "exercise/[id]/". When this route is accessed I take that id from the url like this:

const router = useRouter()
const id = router.query.id

Then I run a SWR fetch (client side fetching) hook to fetch some data from the server with the provided id.

If the user types an id that doesn't exist in the server or if they typed an invalid id like some letters and characters, what's the right way to handle this situation? And is there a way to redirect the user to the default next's 404 page?

CodePudding user response:

What you are describing is not possible in a purely client-side rendered environment.

If you are getting data from the URL, you should be able to server-side render the page and return a 404 before the page ever gets client-side rendered.

If SSR isn't an option, you have to return an entirely different component client-side based on the SWR output. At that point you're not returning a true 404 (as far as the network status code) and would just be rendering a different component based on your API's output.

https://nextjs.org/docs/api-reference/data-fetching/get-static-props#getstaticprops-return-values

If you CANNOT server-side render, then you would have to conditionally render a different component/set of components based on the SWR output. That is entirely dependent on how your code is set up, and even that would not be a true 404 if that matters to you.

  • Related