Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using NextAuth hooks useSession() inside getServerSideProps()

I'm trying to get some data from my server depending on whose currently logged in. I'm using Next-Auth and normally I can just call:

const { data: session } = useSession();

At the top of the functional component, but you cannot do this in getServerSideProps().

I need to make a get request like this:

export async function getServerSideProps() {
  const res = await fetch(
    `http://localhost:5000/api/users/${session.id}/following`
  );
  const isFollowing = res.json();
  return {
    props: { props: isFollowing },
  };
}

that has the current users session ID dynamically put in.

How do I access my session ID inside getServerSideProps?

like image 221
Eric Pezzulo Avatar asked May 18 '26 12:05

Eric Pezzulo


1 Answers

Since useSession is react-hook - it can be used only inside Component. For server-side usage there another method from Next-Auth package - getSession. https://next-auth.js.org/v3/getting-started/client#getsession

Server-Side Example

    import { getSession } from "next-auth/client"

    export default async (req, res) => {
      const session = await getSession({ req })
      /* ... */  
      res.end()
    }

Note: When calling getSession() server side, you need to pass {req} or context object.

like image 192
Vitalii Avatar answered May 21 '26 01:05

Vitalii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!