How do I prevent node from logging an exception to the console in my NextJS/Express app? How do I prevent node from logging an exception to the console in my NextJS/Express app? express express

How do I prevent node from logging an exception to the console in my NextJS/Express app?


I won't pretend to know what's going on, but my best guess is that next.js is logging the error somewhere. I did some digging and it appears there's an error logger in the server code that will log on errors unless a quiet property is set on the server:

https://github.com/zeit/next.js/blob/canary/packages/next-server/server/next-server.ts#L105:

return this.run(req, res, parsedUrl)   .catch((err) => {   this.logError(err)    res.statusCode = 500    res.end('Internal Server Error')})

Here's the sig and body for the logError function:

private logError(...args: any): void {  if (this.quiet) return  // tslint:disable-next-line  console.error(...args)}

If you look at the documentation for using the next API with a custom server, it notes the following options object properties that can be passed to the constructor:

The next API is as follows:

next(opts: object) Supported options:

  • dev (bool) whether to launch Next.js in dev mode - default false

  • dir (string) where the Next project is located - default '.'

  • quiet (bool) Hide error messages containing server information - default false

  • conf (object) the same object you would use in next.config.js - default {}

When constructing the next object, try passing quiet as true to see if it resolves your issue:

const express = require('express')const next = require('next')const port = parseInt(process.env.PORT, 10) || 3000const dev = process.env.NODE_ENV !== 'production'const app = next({ dev, quiet: true })const handle = app.getRequestHandler()

The docs also mentions errors are logged in non-production environments (identified when process.env.NODE_ENV !== 'production'), so I would also check to ensure you're setting NODE_ENV to 'production' when starting your application:

NODE_ENV=production node server.js

I hope this helps!


In express you can setup an ErrorMiddleware.After all your routes declaration, put

 server.use(function(req, res, next) {  handler(req, res).catch(e => {    // use rejected promise to forward error to next express middleware    next(e)  })});

Like this, when you reject a Promise, next(e) will send your error to next middleware. I usually setup a middleware where i send error, and then i manage all errors in one single function (based on statusCode error,...).