Shivan M.
—Occasionally, when building a Next.js application, you might encounter a hard-to-debug error that causes your component (or page) not to render. These client-side exceptions are often caused by a bug in your code, or a third-party API that you depend on.
The best way to identify and fix client-side errors in React and Next.js is through the use of Error Boundaries.
In React, if your application throws an error during rendering, React will remove its UI from the screen.
Error Boundaries allow the other parts of your application to keep working when there is an error in an isolated component or piece of code. It also allows you to provide a fallback component and log error information.
In Next.js, Error Boundaries are used by creating an ErrorBoundary
component:
class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } static getDerivedStateFromError(error) { return { hasError: true } } componentDidCatch(error, errorInfo) { console.log({ error, errorInfo }) } render() { if (this.state.hasError) { return ( <div> <h2>Oops, there is an error!</h2> <button type="button" onClick={() => this.setState({ hasError: false })} > Try again? </button> </div> ) } return this.props.children } } export default ErrorBoundary
This ErrorBoundary
component is then used to wrap the Component
property in pages/_app.js
if you’re using the Pages router.
import ErrorBoundary from '../components/ErrorBoundary' function MyApp({ Component, pageProps }) { return ( <ErrorBoundary> <Component {...pageProps} /> </ErrorBoundary> ) } export default MyApp
Currently, there isn’t a way to write an Error Boundary as a function component for the Pages router in Next.js. If you don’t want to write and maintain the ErrorBoundary
component yourself, you can use a package that implements a reusable component.
If you are using the App router, you can use the error.js
file convention instead. This useful feature of Next.js wraps a route segment and its children in an Error Boundary.
You can use the error.js
convention by creating the file inside a route segment and exporting a React component. Error components must be client components.
'use client' import { useEffect } from 'react' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { useEffect(() => { console.error(error) }, [error]) return ( <div> <h2>Something went wrong!</h2> <button onClick={ () => reset() } > Try again </button> </div> ) }
When a runtime exception is thrown from anywhere in the route segment, the error.js
component is triggered. You can add your own error logging and reporting logic to the useEffect
function. When the Try again
button is clicked in this scenario, the function will try to re-render the contents of the Error Boundary.
Below are a few common causes to look out for when debugging this error.
props
Client-side exceptions can occur when invalid props are passed down from parent to child components. If you’re using TypeScript, it is recommended to strong-type your props so that you can be certain that your components are receiving what they need.
In the following example, we allow our props
to be of type any
, which can result in exceptions when the component is rendered:
interface Props { slug: any; content: any; } export const Post: React.FC<Props> = ({slug, content}) => { // We might assume that `slug` is a URL here } export default function Dashboard() { return ( <div> <Post slug={5} content={"My Content"} /> </div> ) }
To ensure that the Dashboard component uses the Post component correctly, we can strongly type our props
as follows:
interface Props { slug: string; content: string; }
If your application depends on a backend server, there might be an issue with the API response. Ensure that your code can deal with error responses from APIs, as well as failed network requests when APIs aren’t available.
If you are deploying your Next.js application to Vercel (or another hosting provider), check whether you have properly configured the environment variables for your production environment. Compare the contents of your .env
file locally to the environment variables in the dashboard or configuration of your hosting provider.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.