nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.1k stars 3.34k forks source link

getServerSession is null in route handlers when I call the api from server component - next13 app directopry #7693

Closed rezaaa closed 1 year ago

rezaaa commented 1 year ago

Environment

next 13.4.3 and next-auth ^4.22.1

Reproduction URL

-

Describe the issue

Hi

I'm using next 13.4.3 and next-auth ^4.22.1 and this is my API folder:

image

properties/route.ts

export async function GET() {
  const session = await getServerSession(authOptions)
  if (!session) {
    return new Response("Unauthorized", { status: 403 })
  }
  const response = await fetch(`${getApiUrl()}${PROPERTIES}`,
    {
      headers: {
        'content-type': 'application/json',
        "Authorization": `Bearer ${session?.tokens?.access_token}`
      }
    }
  );
  const data = await response.json();
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: {
      'content-type': 'application/json'
    }
  });
}

When I call be API from a server component, the session is null but when I call it from a client component it works!

How to reproduce

-

Expected behavior

-

joulev commented 1 year ago

The reason is that when you fetch route handlers from server components, cookies are not available (it's only available when the request is made from the browser).

This is not a bug; you shouldn't fetch route handlers inside server components, instead just use the route handlers logic in server components directly. Instead of

export default async function Page() {
  const res = await fetch("http://localhost:3000/api/user?uid=123456");
  const user = await res.json();
  return <div>{user?.name}</div>;
}

use

import { prisma } from "~/lib/prisma";

export default async function Page() {
  const user = await prisma.user.findUnique({ where: { id: 123456 } });
  return <div>{user?.name}</div>;
}
balazsorban44 commented 1 year ago

Duplicate. See https://github.com/nextauthjs/next-auth/issues/7423#issuecomment-1531064680

(Please search through old issues before opening a new one. :pray:)

CodeOnTheWall commented 1 year ago

But how would you do a post/delete/patch then? how do we protect the api routes so that people cant send postman requets to our api routes that are respondible for post/patch/delete? would we just still do that on a protected server component and for example if the db is with mongo, we would directly do mongoose methods on our model from the server component instead of doing that logic inside the api route?

Gyurmatag commented 10 months ago

@balazsorban44 what if I want to use server actions but I also want to build an API that is available for the public (with authentication) from my backend Next.js project?