How to access my custom protected API, created in Next JS

I created this api endpoint in next js (let’s call it userData) :


export const GET = withApiAuthRequired(async function GET() {
  await dbConnect();
  try {
    const session = await getSession();
    const user = session?.user;
    const userData = await user_data.find({
      email: user?.email,
    }); /* find all the data in our database */
    return new Response(JSON.stringify({ data: userData }), {
      status: 200,
    });
  } catch (error) {
    return new Response(JSON.stringify({ message: "An error occurred" }), {
      status: 500,
    });
  }
});

I have another endpoint called token, also protected with withApiAuthRequired().
when calling the the userData api from the token api I get

 {
  error: 'not_authenticated',
  description: 'The user does not have an active session or is not authenticated'
}

please how can I fix it?
I want to be able to access it.

Hi @rezgui.aziz,

Thanks for reaching out to the Auth0 Community!

When calling the withApiAuthRequired function, it requires the user to have a valid session which requires them to login.

Could you please clarify if you have logged in before trying to access your protected endpoint?

See handleAuth | @auth0/nextjs-auth0.

Thanks,
Rueben

Hey @rueben.tiow, yes I am sure I am logged in, here is my login handler, maybe the config might caused the issue?

  login: async (req: NextApiRequest, res: NextApiResponse) => {
    try {
      const loginResponse = await handleLogin(req, res, {
        authorizationParams: {
          audience: "https://xxx.auth0.com/mfa/",
          scope: process.env.AUTH0_SCOPE,
          client_id: process.env.AUTH0_CLIENT_ID,
          client_secret: process.env.AUTH0_CLIENT_SECRET,
        },
      });

      return loginResponse;
    } catch (e) {
      console.log(e);
    }
  },

Hi @rezgui.aziz,

Thank you for your reply.

It seems that you would need to call getAccessToken() to correctly get an access token to access an external API from the server. Please check out the example below on accessing an external API from an API route.

Let me know if you have any questions.

Cheers,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.