Part 49: Enhancing Error Handling in Next.js with Fallback and Not Found Pages
[Pages] Data Fetching

In our previous exploration of Next.js, we implemented the fallback: 'blocking' option to dynamically generate pages for new products. This approach ensured that when a new product was added to the CMS, the corresponding page would be automatically generated upon request. However, this setup revealed some challenges, particularly when handling requests for non-existent product IDs. Let's delve into how we can improve our error handling to provide a more robust user experience.
The Issue with Non-Existent Product IDs
When a request is made for a product ID that doesn't exist, such as "99", our application initially resulted in a 500 Internal Server Error. This error occurs because our code attempts to parse a non-existent product's response as JSON, which fails since the response is plain text indicating "Not Found".
Understanding the Error
The root cause of this error lies in the lack of error handling in our getProduct function. When the CMS returns a 404 response for a non-existent product, our code tries to parse this response as JSON, resulting in a FetchError. To address this, we need to check the response status before parsing.
Implementing Error Handling
To improve our error handling, we can modify the getProduct function to throw an error if the response is not successful.
// lib/products.js
export async function getProduct(id) {
const response = await fetch(`http://localhost:1337/products/${id}`);
if (!response.ok) {
throw new Error(`request failed: ${response.status}`);
}
const product = await response.json();
return stripProduct(product);
}Explanation
Response Check: Before parsing the JSON, we check if the response is OK. If not, we throw an error with the status code.
Error Handling: This ensures that our application doesn't attempt to parse an invalid response, preventing the 500 error.
Returning a 404 for Non-Existent Products
Next, we need to modify getStaticProps to handle these errors gracefully by returning a 404 page for non-existent products.
// pages/products/[id].js
export async function getStaticProps({ params: { id } }) {
try {
const product = await getProduct(id);
return {
props: { product },
revalidate: 30, // seconds
};
} catch (err) {
return { notFound: true };
}
}
function ProductPage({ product }) {
// Render the product page here
}Explanation
Try-Catch Block: We use a try-catch block to handle potential errors during data fetching.
Not Found Flag: If an error occurs (e.g., the product doesn't exist), we return
{ notFound: true }, prompting Next.js to display a standard 404 page.
Handling CMS Downtime
While our current setup handles non-existent products, it doesn't account for situations where the CMS is unavailable, such as during maintenance. In such cases, returning a 404 could mislead search engines and users, suggesting that the product no longer exists.
To differentiate between a non-existent product and CMS downtime, further improvements are needed. For now, our focus is on ensuring that 404 pages are only shown for genuinely non-existent products.
Conclusion
By incorporating proper error handling in our getProduct function and using the notFound flag in getStaticProps, we can ensure that our application responds appropriately to requests for non-existent products. This approach not only prevents misleading server errors but also enhances the user experience by clearly indicating when a product doesn't exist.
As we continue refining our application, we'll explore more robust error handling strategies to manage different failure scenarios, such as CMS unavailability, ensuring that our Next.js application remains resilient and user-friendly.
Last updated