DEV Community

Discussion on: Build a full API with Next.js

Collapse
 
noclat profile image
Nicolas Torres • Edited

Thanks a lot! nc().use() requires the function arg to be compatible with the props it receives. If you can't make it work out of the box, you may need to wrap it:

const handler = nc()
  .use(errorHandler)
  .use((req, res, next) => {
    withApiAuthRequired(req, res);
    next();
  })
  .get(async (req, res) => {
    res.status(200).text('Hello world.');
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nordicgit70 profile image
nordic70 • Edited

Thanks for your help! Below a suggestion from my side to replace const handler = nc().use(errorHandler) with const handler = router().

/* Middleware to create a Next connect router. */
export default function router() {
  return nc({
    onNoMatch: (req, res) => res.status(400).send({
      success: false,
      message: `Bad API request: ${req.url}`,
    }),
    onError: (err, req, res) => res.status(500).send({
      success: false,
      message: `Unexpected server error.`,
      error: err.toString(),
    }),
  });
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
noclat profile image
Nicolas Torres

Yeah my original code didn't work, that's a good way to put it. I just wouldn't call it router to avoid confusion, because it's just a handler, the router being managed inside Next core :).