How to properly use protected api routes in Next.js?

Hi, I would like to ask how to properly use protected API Routes in Next.js using Next.js SDK.

In the migration guide from v3 to v4 you mention that withApiAuthRequired has been removed from the SDK, but it’s still there. And it is also used as an example of how to protect API routes in App router.

But when I actually use it, it shows me this typescript error:
The inferred type of 'GET' cannot be named without a reference to '../../../../../../packages/nextjs/node_modules/@auth0/nextjs-auth0/dist/server/helpers/with-api-auth-required'. This is likely not portable. A type annotation is necessary.

I can type it like this, but the NextApiHandleris not for App router API routes is it?

export const GET: NextApiHandler<User> = auth0Client.withApiAuthRequired(fetchUser);

Thanks!

Hi @ronaldruzicka

The method withApiAuthRequired used to protect API routes should still be available in the v4 SDK.

As far as I can see in our documentation regarding the SDK, the method is still available under Auth0Client instance for the server.

The documentation available on the Github repository also shows examples on protecting an API route using that method.

This issue might also occur when you are exporting a function whose return type could not be inferred by TypeScript. You can try adding a type annotation like “data”:

const foo = async () => {
// Add type annotation to `data`
  const data: DoStuffReturnType = someExternalLibary.doStuff(); 
  return data;
};

Also, does your API route use a custom API or one registered within the Auth0 Dashboard? If you do have it registered within Auth0, are you passing in the proper audience? I would recommend that you double check if you are importing all necessary dependencies when you are trying to use the method.

If you still encounter the same issue after following our documentation on the matter, please let me know!

Kind Regards,
Nik