next.js: How to catch and handle errors to report logs on server side
Hi, I’m in the situation where we want to sent errors, both on server and client side, to Sentry tool.
Our app uses Express as a custom server. Basically we create an express app, apply some middlewares but delegate all the real job to the next.js handle:
const app = nextJs({ dev: process.env.NODE_ENV !== 'production' });
const handler = routes.getRequestHandler(app);
const expressApp = express();
...
...
expressApp.use(morgan('combined', { stream: logger.stream }));
expressApp.use(statsdMiddleware);
// Add security
expressApp.use(helmet());
// Sentry handler
expressApp.use(sentry.requestHandler());
// Load locale and translation messages
expressApp.use(i18n);
// Next.js handler
expressApp.use(handler);
// Sentry error handler.
// MUST be placed before any other express error handler !!!
expressApp.use(sentry.errorHandler());
With this approach next.js takes control over the rendering process and any error is catch by next.js and the only way I have to process it is overriding the _error.js page file.
Within that _error.js file I need a universal way to report errors to Sentry. Currently there are two libraries (raven for node and raven-js por javascript). The proble is I can’t import both of them because raven works for SSR but fails when webpack builds the bundle, and also raven-js fails due XMLHTTPRequest dependency too.
Is there a way I can be notified for next.js error on server side?
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 74
- Comments: 97 (34 by maintainers)
This is something we’ve talked about internally. And we’ll be addressing soon.
Gotta love unortodox solutions
It’s super frustrating that a basic need like this still open after 4 years and 10 major releases.
Custom logging and error handling are basic features being neglected from the Next.js team sadly 🥲
I feel like this and lack of guides/prebuilt integrations for apm and error reporting services are a big gap for next.js. I hope this is high on the roadmap. how are large companies even running next.js without these 2 basic things? I guess custom server and prayers 😢
I’m also having this problem. I wonder: would simply returning a rejected promise from next’s
handleRequestbe sufficient? That is, changing the code here to be:Then, in user code:
@kelly-tock okay, I wrote up a quick note about how we use preloading with NextJS: https://jake.tl/notes/2021-04-04-nextjs-preload-hack
It’s unclear, you’d think a framework would provide an idiomatic way to log errors both client and server 🤷♂️
For logging errors in the client side we have been doing the following: https://gist.github.com/jgautheron/044b88307d934d486f59ae87c5a5a5a0
It basically sends errors to the server, that are in the end printed to
stdoutand caught by ourDockerlogging driver. We have successfully caught SSR errors withreact-guardwith no need to override core Next files.Install both
raven(ignore with webpack as suggested in previous comments) andraven-js, then create a helper to instantiate isomorphic Raven, e.g.lib/raven.jsThen you can use it in your
pages/_error.jsand it will work both on server and client side.Hi, 2 things that I still don’t understand regarding this issue:
Anyone had success catching (and handle) exceptions that occur in
getServerSideProps?I’m using Sentry.io to report errors and the solution we apply is:
1- Configure raven-node on server side 2- Configure ravenjs on client side (we made that on
_document.With this two steps we catch any unhandled exceptions both on client and server.
3- Create an
_errorpage. Any error produced once nextjs handles the request (no matter if client or server side) that page is rendered. In thegetInitialPropsmethod of the _error page we report the error to sentry.The way to decide how to load if raven-node or ravenjs is solved importing dynamically depending if we are in client
const Raven = require('raven-js');or server sideconst Raven = require('raven');. Note we have configured webpack to not bundle theravenmodule (the server side one) updatingnext.config.jswith:I’ve been using
@sentry/browserin thegetInitialPropsof_error.jsand it seems to be working both client and server-side. I don’t know if@sentry/browseris supposed to have server-side support, but I am getting events to Sentry.Though I am also calling
Sentry.init()via@sentry/nodein a custom Express server’s entry file, so perhaps that is setting some global state that the SSR is using.Here’s a gist of the setup that I’m using: https://gist.github.com/mcdougal/7bf001417c3dc4b579da224b12776691
@tusgavomelo Sorry, for the late reply.
We have update. In our app we have a helper file with a method responsible to get a Raven instance taking into account if we are on client or server side.
This code runs both server side (when a request arrives) and client side. What we have done is configure webpack (
next.config.jsfile) to avoid bundle theravenpackage._app.js is not client-side only, however
componentDidCatchis@kelly-tock if you have control of Next’s invocation, you can do this without a “custom server” using a “preload”. If you can invoke next like
node -r yourCrazyPreloadMonkeyPatches.js node_modules/.bin/nextyou can preload arbitrarily code without losing automatic static optimization. At Notion we run Next on AWS Beanstalk and use this technique to load Datadog APM into the process, and monkey-patchglobal.console.logandglobal.console.errorto use our error reporting logic.Interesting!
There’s definitely some kind of global state going on here (which is a bit scary, and probably brittle and undesirable). Applying your changes in
_error.js:ReferenceError: XMLHttpRequest is not definederror in the server logsError: Sentry syntheticExceptionrecorded in SentryIt would be good to understand what the official solution is. Next’s docs seem to recommend using a custom
<App>component now, and that’s what the “with Sentry” example does, but this only works for the client side.a quick recap for anyone who investigating on this problem.
thanks to @acanimal 's comment.
Compact version of how to get correct Raven for node and browser w/o custom webpack config. Inspired by @acanimal comment
Gist
thanks for writing that out but indeed we need a generic “error handler” for the server like pretty much any express.js production app will end up having so unexpected errors can be caught, a user-friendly 500 can be return and the error can be sent to any error reporting library.
fingers crossed this will be sorted out soon as it’s rather important.
@justjake Thanks for the excellent writeup! While having to monkey-patch logging is a shame, I think using
--requirefor adding instrumentation/error handling is fairly “elegant” as far as these things go.Sentry just released a new official Next.js SDK that has an interesting approach: it actually injects Sentry setup into the Webpack bundles for your app, both the client and server (https://github.com/getsentry/sentry-javascript/blob/master/packages/nextjs/src/utils/config.ts#L154-L155). Unfortunately, we’re using Rollbar at my company, and Rollbar doesn’t have any Next.js integration, so we’ll have to do a manual setup. The
--requireroute seems much easier, but I wonder if maybe the Webpack solution has some other advantages I’m missing (besides not having to remember to use different command line arguments).In general, I think Next.js docs should incorporate discussion of error reporting. I had deferred adding error handling to the “last 10% work” of a new project launch and spent yesterday in a bit of a panic trying to figure out how on earth I was going to add it. I had just assumed it’d be as easy as adding Sentry/Rollbar/Bugsnag/etc usually is - just add it to the entry point - until I realized Next has no “entry point” without a custom server. If the use of
--requireto register such things is the “happy path” for Next apps, I think it absolutely needs to be documented, rather than be buried here in a 4 year old GitHub issue.I’m not sure what’s meant to be done here (why is this issue still open? What’s the plan?)
But error handling with Next was very complicated, there are a lot of use cases and places to catch errors from.
I added Sentry built-in in Next Right Now, if you’re struggling about how to configure Sentry on either backend or frontend, you might want to take a look. All Next.js errors are caught and sent to Sentry, whether client side, server side, build issue, page loading crashes, CSR crashes, etc.
If you think I missed anything, tell me!
Kinda spent a few months improving those bit by bit, should be a great starting point.
Tbh i am very confused on what the correct places to catch errors for next.js are right now. There are _app.tsx, _error.tsx and _document.tsx there are some comments saying that some stuff should be caught in _error.tsx (like: https://github.com/zeit/next.js/pull/5727/files#r235981700) but the current examples use either _app.tsx or _app and _document.
I tried both ways now and it seems that some errors that happen during ssr are not getting caught for me. Which places are now the correct ones to check for errors? The most logical one for me seems to check in the componentDidCatch of _app and the getInitialProps of the _error as this one is being served in cases of errors. I am a bit confused about the whole
process.onpart in the _documentCould someone with more in depth knowledge please resolve this question?
I was having a lot of trouble using the
with-sentryexample, so I opened up a PR for a much more simple example. It doesn’t have all the bells and whistles, but it’s been working for me.https://github.com/zeit/next.js/pull/7119
The only thing one needs in next.js is ability to add custom middleware in next.config.js and something like next.browser.js for universal (isomorphic) plugin configuration (next.config.js is used among others for webpack configuration, which means other things defined in this file cannot be used in application code, because it would cause circular dependency).
For next.browser.js next.js could define configuration like decorator for App or Document components. This way I could implement sentry integration entirely as a plugin.
EDIT: I don’t know whether there is ticket for this, but I think @timneutkens is already extracting next server into separate packages. I think best plugin interface would be something like:
Next.js still outputs errors to
console.erroron the server as long as you don’t set it to quiet.With Sentry, you can enable
autoBreadcrumbsto capture this output, and then capture your own message manually. The title will be less descriptive, but it will still contain the full stack trace.Example implementation:
This is a very contrived example adapted from our actual code. I haven’t tested it in this form. Let me know if it breaks.
Of course, it would still be best if Next.js could pass those errors around to Express, so that we can use the Sentry/Express integration out of the box.
@thomasboyt Thanks for pointing out Sentry released something for Next.js! I’m gonna take a look at it very soon!
For anyone interested: https://sentry.io/for/nextjs/
Also, we mentionned logging above, and we’ve released https://github.com/UnlyEd/simple-logger a few days ago, which is 1kB an universal. After trying out a lot of open source alternatives, we couldn’t find something that felt just right. Maybe you’ll find it as useful as we do!
Same to you folks. with-sentry example doesn’t allow lazy loading, as well as it doesn’t catch errors before app initialization. Moreover there are can be errors in your custom ssr server which are also want to be tracked with sentry. So these days I see such issues with setup of sentry error tracking with nextjs which are not covered by any guide:
I’ve been struggling with monkey-patching all the different parts of Next.js that log errors on the path to using Next.js for Notion’s new marketing site. It’s been a frustrating experience; I’m up to patching
global.console.log = myCustomLoggingFunctionat this point.So now that we have a necessarily complex working example, what are the next steps to improve the situation:
Here it goes… https://github.com/zeit/next.js/pull/5727
Here are my extra notes about custom _app component and error handling:
_app.jsis used for ALL pages, including_error.jsor pages like 404 so you really want to be sure no error is thrown whenctx.erris passed to it…_error.jsto be called (call it even ifctx.erris present)So far I find properly setting up error reporting in next.js a very fragile procedure 😦
@sheerun I’m hitting the same issue. Using
@sentry/nodeisn’t trivial. The readme for this Sentry example suggests using a custom server, which we already have in the application I’m working on. To capture exceptions in our custom Express.js server, you need to insert a Sentry error handler middleware error as the first error handling middleware. If you insert Sentry’s error handler straight after the Next handler, the error has already been swallowed by that point and Sentry doesn’t see it.The errors details are also available on the stderr stream.
process.stderr.write = error => yourErrorLog(error);@kelly-tock Next Right Now uses Sentry for monitoring (front + back + api) https://github.com/UnlyEd/next-right-now/
Running about 20 projects using Next.js (most of them using NRN) I totally feel you regarding monitoring, it’s a must-have for confidence.
Regarding logging though, I haven’t found a solution that satisfies me. I hope it comes built-in.
It’s definitely a priority! And no, you wouldn’t need a custom server:
getServerSidePropsand forward it to their provider of choiceHope this helps in the meantime.
Glad to hear that! I’m currently working on a proposal for switching to next, and performance monitoring and error handling will be key. Any ideas on timelines? And for both APM and error logging services, we’re left to do custom servers for now right?
@stephankaag
yes, something like this worked for me:
first create a middleware to handle the crash reporting. I’ve wrapped
Sentryinside theCrashReporterclass because simply returningSentrywill not work (i.e.req.getCrashReporter = () => Sentry).next, of course, load the middleware into your app before the Next.js request handler is set:
then wherever you call
getServerSideProps:@abraxxas
process.onin_document.jsis catching errors that happen on the server. As a recap,_document.jsis server-side only and is used to change the initial server-side rendered document markup._app.jsis client-side only and is used to initialize pages.Therefore, when an error happens on the server it should throw an error to Sentry via
process.onand then the client will render the default error page or_error.js.Hopefully this will help: https://leerob.io/blog/configuring-sentry-for-nextjs-apps/