How to handle errors
Learn how to display expected errors and handle uncaught exceptions.
Errors can be divided into two categories: expected errors and uncaught exceptions. This page will walk you through how you can handle these errors in your Next.js application.
Handling expected errors
Expected errors are those that can occur during the normal operation of the application, such as those from server-side form validation or failed requests. These errors should be handled explicitly and returned to the client.
Server Actions
You can use the useActionState
hook to manage the state of Server Functions and handle expected errors. Avoid using try
/catch
blocks for expected errors. Instead, you can model expected errors as return values, not as thrown exceptions.
Then, you can pass your action to the useActionState
hook and use the returned state
to display an error message.
Server Components
When fetching data inside of a Server Component, you can use the response to conditionally render an error message or redirect
.
Not found
You can call the notFound
function within a route segment and use the not-found.js
file to show a 404 UI.
Handling uncaught exceptions
Uncaught exceptions are unexpected errors that indicate bugs or issues that should not occur during the normal flow of your application. These should be handled by throwing errors, which will then be caught by error boundaries.
Nested error boundaries
Next.js uses error boundaries to handle uncaught exceptions. Error boundaries catch errors in their child components and display a fallback UI instead of the component tree that crashed.
Create an error boundary by adding an error.js
file inside a route segment and exporting a React component:
Errors will bubble up to the nearest parent error boundary. This allows for granular error handling by placing error.tsx
files at different levels in the route hierarchy.
Global errors
While less common, you can handle errors in the root layout using the global-error.js
file, located in the root app directory, even when leveraging internationalization. Global error UI must define its own <html>
and <body>
tags, since it is replacing the root layout or template when active.