Search⌘ K
AI Features

Graceful Error Handling Patterns

Explore how to handle loading, success, and error states in Next.js using declarative error boundaries with error.js and the notFound() function. This lesson helps you implement robust fallback UIs for failed API requests or missing resources, ensuring your application remains interactive and user-friendly during errors.

Previously, we saw how loading.js lets us stream UI and show an immediate loading state. Now we’re going to expand that idea. Whenever an application fetches data, it moves through three states: a loading state while we wait, a success state when the data arrives, and an error state when something goes wrong. A well-designed interface handles all three cleanly.

In this lesson, we’ll walk through the full declarative pattern that Next.js provides for managing this lifecycle.

Fallback UI with error.js

Creating an error.js file inside a route directory creates a safety net for failures in that specific segment. In Next.js, this is referred to as a React Error Boundary.

If something goes wrong while rendering a page or its children, such as a failed API request or a database issue, the boundary catches the error. Instead of the entire application collapsing to a blank screen, only the affected segment is replaced by the component exported from error.js. The rest of the application, like shared navigation and layouts, remains intact and interactive.

Error components are always Client Components, because they need to be interactive to support recovery. They receive two key props:

  • error: It is a JavaScript Error object that includes the message and stack trace. It’s useful for logging or debugging. ...