When I do server side rendering which involves fetching from database or external API, I always assume that the operation can fail for a few reasons:
- The database server was down.
- The external API server I’m using is unreachable.
This is a minimal sample of the SSR code that can fail
Next.js will show a default error page that looks like this
Developers are used to seeing this, but non-technical users are not.
Showing default error like this can confuse non-technical users and even scare them.
Did I do something wrong that caused this?
I just paid money and this is all I got? This website is a scam!
That’s why I prefer to show a customized error page that shows a more user friendly error message.
This gives our users relief that they’re not in the wrong.
Fortunately Next.js provides us a way to do this, and I’m going to show you how in this post.
Displaying custom error pages
All you need to do is to add error.tsx to handle custom error in your pages.
The code on page.tsx remains the same, you don’t need to change anything. This keeps the pages code simple and clean.
Any errors that are thrown in page.tsx will cause Next.js to render error.tsx instead.
Let’s see how the error.tsx should look like
This is a good place to show a user friendly error message and assure the users that everything will be fine.
I can also provide a retry button to redo the SSR operation if I want. Next.js already provided a reset function that does exactly this.
Showing 404s or non-existing resources
In a typical CRUD application, viewing a specific resource is a very common use case. For example:
- Viewing a product detail
- Viewing a blog post
- Viewing a tweet
- Viewing an Instagram post
- And so many more
The common pattern between them is usually the url contains a specific id like /product/[productId]
or /post/[postId]
.
I always assume that at some point a user will visit the url with an invalid id because of the following reasons:
- Users could type or copy-pasted the wrong URL
- The resource used to exist but not anymore.
Next.js provides a simple way to show 404 pages.
When the resource is not found, the browser will get 404 response from the server and a page that looks like this.
It works but looks off, making the site looks somewhat unprofessional.
NextJS provides a way to customize my 404 page so it blends more with my site’s design.
Make it specific
We can utilize Next.js App Router capability to provide custom error between layouts.
This makes it easy for the users to tell where the errors are happening.
For example, I can show different errors 404 pages when visiting different urls.
And each page shows relevant error messages instead of generic ones:
-
Shop error page
-
Shop not found page
-
Product error page
-
Product not found page