Why is the session unavailable when I fetch the session route in next-auth from my server component?

I'm having this function

async function getSession() {
  const response = await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`);
  return getSessionFromNextAuthResponse(response);

But it is not working when I try it in a server component

async function Component() {
  const session = await getSession();
  return null;

Why is that? It used to work inside the pages directory…

The cause is that the place that call this getSession function has changed. In the pages directory, the function was called in the browser, but in server components the function is called from your server.

When the fetch is run from the browser, it automatically carries over all the relevant cookies that next-auth uses to identify the session. That is why it worked. But now, when the fetch is run from the server, it does not carry over the cookies, and the session is not found. It is like if you request that endpoint using curl in your terminal; there are no cookies automatically sent, you have to manually add cookies to the request if necessary.

For next-auth, you have getServerSession which can do exactly what that getSession is supposed to do, so just use it instead of trying to make your own session retrieval function.

Generally speaking, you should not fetch your own route handlers (like /api/auth/session in this case) inside your own server. For more details, see   Fetching own API endpoint in React Server Components. Note that this does not apply to external server, e.g. your separate Express server. In that case, whether you should do this depends on many factors.