DEV Community

Discussion on: Build a full API with Next.js

Collapse
 
svobik7 profile image
Jirka Svoboda

Thank you for great article. Just quick note that this is not working for me now:

export const secureHandler = nc()
  .use(errorHandler) // we reuse a next-connect instance
  .use(apiLimiter)
  .use(bearerAuth)
  .use(acl);
Enter fullscreen mode Exit fullscreen mode

The only way for me is to specify onError and onNotFound directly on nc instance:

export const secureHandler = nc({
  onNoMatch: (req, res) => res.status(404).send({
    ok: false,
    message: `API route not found: ${req.url}`,
  }),
  onError: (err, _req, res) => res.status(500).send({
    ok: false,
    message: `Unexpected error.`,
    error: err.toString(),
  }),
})
  .use(apiLimiter)
  .use(bearerAuth)
  .use(acl);
Enter fullscreen mode Exit fullscreen mode

Otherway the initial error callbacks are invoked.

Collapse
 
noclat profile image
Nicolas Torres • Edited

Thanks! Indeed, my workaround here is to define a function that returns a new instance of a base handler:

export const baseHandler = () => nc({
  // 404 error handler
  onNoMatch: (req, res) => res.status(404).send({
    message: `API route not found: ${req.url}`,
  }),

  // 500 error handler
  onError: (err, req, res) => res.status(500).send({
    message: `Unexpected error.`,
    error: err.toString(),
  }),
});

export const secureHandler = baseHandler()
  .use(apiLimiter)
  .use(bearerAuth)
  .use(acl);
Enter fullscreen mode Exit fullscreen mode

Article updated :).