DEV Community

Cover image for Error tracking and monitoring in Next.js
Gogulaanand
Gogulaanand

Posted on • Updated on

Error tracking and monitoring in Next.js

Error tracking and performance monitoring is crucial to any application running in production. Simply because we cant expect the end user to report every issue they face and it is our responsibility to proactively check for errors and fix them for better user experience.

In Next.js, it is very easy to setup error tracking in couple of minutes with Sentry

Lets begin 🚀

Setup

// install sentry's nextjs sdk
npm install --save @sentry/nextjs

// run the setup wizard
// We need to have an account with sentry before running 
// setup as it will open login window in browser
npx @sentry/wizard -i nextjs
Enter fullscreen mode Exit fullscreen mode

We can allow sentry to capture errors in couple of ways.

1.Error object:

try{
  aFunctionThatMightFail();
}
catch(err){
  throw new Error(err)
}
Enter fullscreen mode Exit fullscreen mode

2.Use Sentry's methods to capture the error:

import * as Sentry from "@sentry/nextjs";

try {
  aFunctionThatMightFail();
} catch (err) {
  Sentry.captureException(err);
}
Enter fullscreen mode Exit fullscreen mode

Alternatively, we can use React's Error boundary to log the error to Sentry

import * as Sentry from "@sentry/nextjs";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };  
  }

  componentDidCatch(error, errorInfo) {
    // we can log error or errorInfo to Sentry here.
    // errorInfo will contain the details 
    // and stack trace which is better for debugging

    Sentry.captureException(errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;    
    }
    return this.props.children; 
  }
}
Enter fullscreen mode Exit fullscreen mode

And...
We are done. 🎉
Now the Sentry SDK will automatically capture unhandled errors and promise rejections, and monitor performance in the client.


Lets have a look at what Sentry offers:

Main sentry dashboard

Main dashboard

Issues dashboard of sentry

Issues dashboard

We get an overview of all the issues at one place. We can also view release wise report.

Once, while checking something in my local, some error flashed up during page transition for a second and then disappeared. I couldnt reproduce it again, log was not available in terminal or browser console but it was logged in sentry with full error trace 😄


Performance dashboard of sentry

Performance dashboard (Similar to Chrome's Light House performance report)

📌 We get active support for sentry in next.js which is a good thing in the long run (eg: Recent update: Next.js v11.1). To explore more, checkout Sentry's guide for nextjs

Credits: Cover Photo by Luke Chesser on Unsplash

Top comments (0)