DEV Community

Discussion on: Build a full API with Next.js

Collapse
 
nordicgit70 profile image
nordic70

Great article and nice clean code. I want to follow your approach but do not get it working with withApiAuthRequired (nextjs-auth0). Could you point me in the right direction? Keep getting the error 'invalid hook call'.

const handler = nc()
  .use(errorHandler)
  .get(async (req, res) => {
    res.status(200).text('Hello world.');
});
Enter fullscreen mode Exit fullscreen mode
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 :).

Collapse
 
schiemon profile image
Szymon Habrainski

Here is my strategy:

import { NextApiRequest, NextApiResponse } from "next";
import { withApiAuthRequired } from "@auth0/nextjs-auth0";
import nc from "next-connect";

// Secured api endpoint.
// Possible synergy between next-connect and withApiAuthRequired from nextjs-auth0.

const handler = withApiAuthRequired(
  nc<NextApiRequest, NextApiResponse>()
    .get(
      (req: NextApiRequest, res: NextApiResponse) => {
        // ...
      }
    )
    .post(
      (req: NextApiRequest, res: NextApiResponse) => {
        // ...
      }
    )
);

export default handler;
Enter fullscreen mode Exit fullscreen mode