I recently switched my site from Gatsby to Next while still deploying to Netlify. For the most part, it went very well. I’ll write some more soon about the transition and some of the challenges that arose.
Today I’m going to cover an issue that I ran into after deploying my site to Netlify. The problem is that if someone were to go to a blog post that didn’t exist, like https://joelmturner.com/blog/abc, they would receive a 500 error message. Since it’s a 500 from the server, the client doesn’t spin up and I can’t see which page was trying to be accessed.
This had me searching all over for the root cause since it all worked locally and I would expect that it would just throw a 404 error like other missing pages. Finally, after searching for quite some time, I came across a GitHub issue that resembled my problem. Sure enough, hu0p had a workaround that worked for me as well.
The factors that lead to this issue are:
- Hosted on Netlify
- Running the Essential Next.js plugin (the culprit)
- Static site build of Nextjs
- Have some dynamic routes like
- Hit a route that doesn’t exist on that dynamic route
By wrapping the data fetching with a try/catch, we are able to return
notFound: true which will trigger the 404 page. I wasn’t aware that
notFound was a return value until I saw this workaround.
We use try/catch: