2

i'm having a problem when i request GET to my api it returns me unauthenticated even though im logged in

my api code basically getSession returns null when im fetching on getServerSideProps but when im fetching on client side (useEffect it works perfectly)

i wanted a ssr that's why im trying to fetch in getServerside props

const handler = async (req, res) => {
    if (req.method === "GET") {
     const session = await getSession({ req });

    if (!session) {
      res.status(401).json({ message: "Not Authenticated" });
      return;
    }
    const userId = session.user.id;
    const client = await connectDb();
    const db = client.db();
    const tasks = await db
      .collection("tasks")
      .find({ user_id: userId })
      .toArray();
    res.status(200).json(tasks);
  }
};

when i try to fetch on serverside it returns me message: "Not Authenticated"

export const getServerSideProps = async (context) => {

  const res = await fetch(`http://localhost:3000/api/tasks`);
  const data = await res.json();
  return {
    props: { data },
  };
};

but when i fetch using useEffect (Client side) it works

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(`http://localhost:3000/api/tasks`);
      const data = await res.json();
      console.log(data);
    };
    fetchData();
  }, []);

sorry i'm still new with this thank you in advance

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Mark Dev
  • 170
  • 1
  • 11
  • That's because the cookies are not sent by default when you make the request from the server inside `getServerSideProps`. You have too to pass the cookies explicitly as described in [Why are cookies not sent to the server via getServerSideProps in Next.js?](https://stackoverflow.com/a/69058105/1870780). – juliomalves Apr 04 '22 at 17:55
  • However, in this case you should not call an internal API route from inside `getServerSideProps`. Instead, you should call the logic that's in the API route directly. See [Internal API fetch with getServerSideProps?](https://stackoverflow.com/a/65760948/1870780). – juliomalves Apr 04 '22 at 17:56
  • 1
    Hi @juliomalves thanks for your response i'll take a look on the resources you give – Mark Dev Apr 05 '22 at 02:19

0 Answers0