The API calls using nextjs-auth0 are always showing as unauthenticated

I have created a Next.JS 14 application, using Auth0, based on the “@auth0/nextjs-auth0” library.
Login, session and protecting pages works fine.

I also implemented DB data fetching through an internal API system. When I run the fetch command, I can see the appSession cookie in the headers of the request in the browser developer tools network tab.
I want to secure the API endpoints using the session created during the login.

At first, I tried to use the provided function from the library:


import { withApiAuthRequired } from '@auth0/nextjs-auth0'

const GET = withApiAuthRequired(async (req: NextRequest) => {

But I always get the error:

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

I then tried to check that the session is authenticated in the API handler directly:

import { getAccessToken , getSession } from '@auth0/nextjs-auth0'

export const GET = async (request) => {
    const session = await getSession(request, res)
    const { accessToken } = await getAccessToken()

In all cases, even though I have the cookie in the request, both session and accessToken are undefined.
I’ve also tried providing the request and response objects to these functions, but there is no change.

Furthermore, I tried to push the access token as an Authorization header as described here:

and that header did not appear on the call’s headers.

I’m at my wit’s end. Can anyone please help me resolve this?

1 Like

Hi I am currently also having this issue, were you able to fix this yet and if so how?

I was actually just able to fix it by putting my async fetching in a useEffect in my component, if you want you can reply with more information and I would be more than happy to try and help you with you current issue :slight_smile:

Thanks, @RaphyPoo. I check and you seem to be correct. when the request comes from a client component, the session is there. When it’s a server component, (and thus no useEffect), it is not.
This is, however, not a perfect solution. My system is mixed. I do have some client components, but I also have some server components I’d rather not convert to client side. This means that I have an inconsistent API interface which sometimes lets my fetches through and sometimes does not.
All very frustrating.

Oh I see, I actually switched all of my components to CSR because I was having trouble with the whole hydration and using the two types of rendering together (I know it kind of removes the entire purpose of NextJS but whatever). However I’m not sure how your api and everything is set up but for me, all of my authentication is done server side. So I only use auth0 on the frontend for the { user } = useUser() from ‘@auth0/nextjs-auth0/client’. maybe you could try implementing it all on the backend and see how that works? I wish you best of luck!