Error Handling
Errors can be divided into two categories:expected errors anduncaught 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 fromserver-side form validation or failed requests. These errors should be handled explicitly and returned to the client.
Server Functions
You can use theuseActionState hook to handle expected errors inServer Functions.
For these errors, avoid usingtry/catch blocks and throw errors. Instead, model expected errors as return values.
'use server'exportasyncfunctioncreatePost(prevState:any, formData:FormData) {consttitle=formData.get('title')constcontent=formData.get('content')constres=awaitfetch('https://api.vercel.app/posts', { method:'POST', body: { title, content }, })constjson=awaitres.json()if (!res.ok) {return { message:'Failed to create post' } }}You can pass your action to theuseActionState hook and use the returnedstate to display an error message.
'use client'import { useActionState }from'react'import { createPost }from'@/app/actions'constinitialState= { message:'',}exportfunctionForm() {const [state,formAction,pending]=useActionState(createPost, initialState)return ( <formaction={formAction}> <labelhtmlFor="title">Title</label> <inputtype="text"id="title"name="title"required /> <labelhtmlFor="content">Content</label> <textareaid="content"name="content"required /> {state?.message&& <paria-live="polite">{state.message}</p>} <buttondisabled={pending}>Create Post</button> </form> )}Server Components
When fetching data inside of a Server Component, you can use the response to conditionally render an error message orredirect.
exportdefaultasyncfunctionPage() {constres=awaitfetch(`https://...`)constdata=awaitres.json()if (!res.ok) {return'There was an error.' }return'...'}Not found
You can call thenotFound function within a route segment and use thenot-found.js file to show a 404 UI.
import { getPostBySlug }from'@/lib/posts'exportdefaultasyncfunctionPage({ params }: { params: { slug:string } }) {const {slug }=await paramsconstpost=getPostBySlug(slug)if (!post) {notFound() }return <div>{post.title}</div>}exportdefaultfunctionNotFound() {return <div>404 - Page Not Found</div>}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 anerror.js file inside a route segment and exporting a React component:
'use client'// Error boundaries must be Client Componentsimport { useEffect }from'react'exportdefaultfunctionError({ error, reset,}: { error:Error& { digest?:string }reset: ()=>void}) {useEffect(()=> {// Log the error to an error reporting serviceconsole.error(error) }, [error])return ( <div> <h2>Something went wrong!</h2> <buttononClick={// Attempt to recover by trying to re-render the segment ()=>reset() } > Try again </button> </div> )}Errors will bubble up to the nearest parent error boundary. This allows for granular error handling by placingerror.tsx files at different levels in theroute hierarchy.


Error boundaries don’t catch errors inside event handlers. They’re designed to catch errorsduring rendering to show afallback UI instead of crashing the whole app.
In general, errors in event handlers or async code aren’t handled by error boundaries because they run after rendering.
To handle these cases, catch the error manually and store it usinguseState oruseReducer, then update the UI to inform the user.
'use client'import { useState }from'react'exportfunctionButton() {const [error,setError]=useState(null)consthandleClick= ()=> {try {// do some work that might failthrownewError('Exception') }catch (reason) {setError(reason) } }if (error) {/* render fallback UI */ }return ( <buttontype="button"onClick={handleClick}> Click me </button> )}Note that unhandled errors insidestartTransition fromuseTransition, will bubble up to the nearest error boundary.
'use client'import { useTransition }from'react'exportfunctionButton() {const [pending,startTransition]=useTransition()consthandleClick= ()=>startTransition(()=> {thrownewError('Exception') })return ( <buttontype="button"onClick={handleClick}> Click me </button> )}Global errors
While less common, you can handle errors in the root layout using theglobal-error.js file, located in the root app directory, even when leveraginginternationalization. Global error UI must define its own<html> and<body> tags, since it is replacing the root layout or template when active.
'use client'// Error boundaries must be Client ComponentsexportdefaultfunctionGlobalError({ error, reset,}: { error:Error& { digest?:string }reset: ()=>void}) {return (// global-error must include html and body tags <html> <body> <h2>Something went wrong!</h2> <buttononClick={()=>reset()}>Try again</button> </body> </html> )}API Reference
Was this helpful?